2013-03-19 84 views
3

這是我做的創建和我的文件中寫道:C#文件處理 - 創建一個文件,並打開

Create_Directory = @"" + path; 
    Create_Name = file_name; 

    private void Create_File(string Create_Directory, string Create_Name) 
    { 
     string pathString = Create_Directory; 
     if (!System.IO.Directory.Exists(pathString)) { System.IO.Directory.CreateDirectory(pathString); } 

     string fileName = Create_Name + ".txt"; 
     pathString = System.IO.Path.Combine(pathString, fileName); 
     if (!System.IO.File.Exists(pathString)) { System.IO.File.Create(pathString); } 

     ///ERROR BE HERE: 
     System.IO.StreamWriter file = new System.IO.StreamWriter(pathString); 
     file.WriteLine(Some_Method(MP.Mwidth, MP.Mheight, MP.Mtype, "")); 
     file.Close(); 
    } 

這裏的問題,我已經奮戰了整整一天,之後我寫文件創造它。所以,我的程序創建一個文件就好了,然後寫入之前給出了一個錯誤:

「類型‘System.IO.IOException’未處理的異常出現在mscorlib.dll」

「附加信息:進程無法訪問文件'D:\ Projects \ Project 15 \ Project 15 \ world \ world maps \ A.txt',因爲它正在被另一個進程使用。「有趣的是,當我再次運行程序並嘗試創建一個已經存在的文件時,就像你看到的那樣,它跳過了文件創建,寫入和工作正常,我真的希望我的程序創建文件和寫入,而不必重新運行它...我在這裏沒有看到什麼? :S

回答

5

問題是File.Create返回一個打開的Stream,並且您從不關閉它。該文件在您創建StreamWriter時正在使用(由您)。

這就是說,你不需要「創建」文件。 StreamWriter會自動爲你做。只刪除這一行:

if (!System.IO.File.Exists(pathString)) { System.IO.File.Create(pathString); } 

而且一切都應該寫作。

注意,我不過稍顯改寫這個,使其更安全:

private void Create_File(string directory, string filenameWithoutExtension) 
{ 
    // You can just call it - it won't matter if it exists 
    System.IO.Directory.CreateDirectory(directory); 

    string fileName = filenameWithoutExtension + ".txt"; 
    string pathString = System.IO.Path.Combine(directory, fileName); 

    using(System.IO.StreamWriter file = new System.IO.StreamWriter(pathString)) 
    { 
     file.WriteLine(Some_Method(MP.Mwidth, MP.Mheight, MP.Mtype, ""));  
    } 
} 

您也可以只使用File.WriteAllText或類似的方法來避免創建的文件這種方式。使用using塊可保證文件將被關閉,即使Some_Method引發異常。

+0

我可以在這裏看到很多有用的建議,我會盡力它出來了,我認爲這會做:) – 2013-03-19 00:30:38

+0

一個問題,但如果我的文件已經存在,會發生什麼,我試圖做出另一個同名的? 編輯:我發現了,它只是重寫它,幸運的是我已經設法將我的舊代碼與你融合在一起,並找到了適合我的東西,謝謝大家:D – 2013-03-19 00:34:59

2

您可以使用File類,因爲它包裝了很多工作,爲您

例子:

private void Create_File(string Create_Directory, string Create_Name) 
{ 
    string pathString = Create_Directory; 
    if (!System.IO.Directory.Exists(pathString)) { System.IO.Directory.CreateDirectory(pathString); } 

    pathString = System.IO.Path.Combine(pathString, Create_Name + ".txt"); 
    File.WriteAllText(fileName, Some_Method(MP.Mwidth, MP.Mheight, MP.Mtype, "")); 
} 
+0

感謝您的信息:) – 2013-03-19 00:40:20

0
static void Main(string[] args) 
     { 
      FileStream fs = new FileStream("D:\\niit\\deep.docx", FileMode.Open, FileAccess.Read); 
      StreamReader sr = new StreamReader(fs); 
      sr.BaseStream.Seek(0, SeekOrigin.Begin); 
      string str = sr.ReadLine(); 
      Console.WriteLine(str); 
      Console.ReadLine(); 

     } 
+0

上面的程序閱讀並打開已在計算機內創建的文件。 – 2014-07-22 20:19:28