2010-05-06 51 views
86

正在被另一個進程使用的文件我試圖檢測一個文件是否在運行時存在,如果沒有,請創建它。但是,當我嘗試寫入該錯誤時,出現以下錯誤:File.Create()

進程無法訪問文件'myfile.ext',因爲它正在被另一個進程使用。

string filePath = string.Format(@"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
if (!File.Exists(filePath)) 
{ 
    File.Create(filePath); 
} 

using (StreamWriter sw = File.AppendText(filePath)) 
{ 
    //write my text 
} 

關於如何解決它的任何想法?

回答

89

File.Create方法創建的文件,並打開該文件FileStream。所以你的文件已經打開了。你並不真的需要file.Create方法都:

string filePath = @"c:\somefilename.txt"; 
using (StreamWriter sw = new StreamWriter(filePath, true)) 
{ 
    //write to the file 
} 

StreamWriter構造布爾會導致文件是否存在內容被追加。

22

當創建您可以使用下面的代碼的文本文件:

System.IO.File.WriteAllText("c:\test.txt", "all of your content here"); 

從您的評論使用代碼。您創建的文件(流)必須關閉。 File.Create的FILESTREAM返回到剛纔創建的文件:

string filePath = "filepath here"; 
if (!System.IO.File.Exists(filePath)) 
{ 
    System.IO.FileStream f = System.IO.File.Create(filePath); 
    f.Close(); 
} 
using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath)) 
{ 
    //write my text 
} 
+0

我似乎沒有收尾選項。這裏是代碼: string filePath = string.Format(@「{0} \ M {1} .dat」, ConfigurationManager.AppSettings [「DirectoryPath」], costCentre);如果(!File.Exists(filePath)) { File.Create(filePath); } 使用(StreamWriter的SW = File.AppendText(文件路徑)){ // 寫我的文字 } – Brett 2010-05-06 13:23:27

+0

'File.Create'返回'FileStream'和具有'關閉()' – 2015-09-07 20:49:04

9

File.Create返回一個FileStream。當您寫入文件時,需要關閉該文件:

using (FileStream fs = File.Create(path, 1024)) 
     { 
      Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file."); 
      // Add some information to the file. 
      fs.Write(info, 0, info.Length); 
     } 

您可以使用using來自動關閉文件。

+0

雖然OP試圖打開一個['StreamWriter'](https://msdn.microsoft.com/en-us/library/system.io.streamwriter(v = vs.110).aspx),可以使用[' File.AppendText'](https://msdn.microsoft.com/en-us/library/system.io.file.appendtext%28v=vs.110%29.aspx)。 – binki 2016-11-29 18:55:34

8

我用代碼片段更新了你的問題。正確縮進後,立即清楚問題是什麼:您使用File.Create(),但不要關閉它返回的FileStream

這樣做是不必要的,StreamWriter已經允許附加到現有的文件如果它還不存在,創建一個新的文件。就像這樣:

string filePath = string.Format(@"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
    using (StreamWriter sw = new StreamWriter(filePath, true)) { 
    //write my text 
    } 

其中採用this StreamWriter constructor

110
File.Create(FilePath).Close(); 
    File.WriteAllText(FileText); 
+3

這很有用。 – Siva 2011-10-01 16:03:51

+4

我喜歡所有其他答案如何太複雜。人們沒有意識到每個問題都有一個更簡單的答案。 – 2011-11-23 01:08:43

+13

該代碼的缺點是它不必要地打開文件兩次。另外,根本不需要檢查文件是否存在,因爲如果FileStream不存在,FileStream構造函數將自動爲您創建它,除非您明確告訴它不要這樣做。 – reirab 2013-08-09 14:02:11

1

這個問題已經回答了,但這裏是 檢查目錄存在,並增加了一個數字結束時,如果該文本文件 存在一個真實的世界的解決方案。我使用它在我寫的Windows服務上創建每日日誌文件。我希望這可以幫助某人。

// How to create a log file with a sortable date and add numbering to it if it already exists. 
public void CreateLogFile() 
{ 
    // filePath usually comes from the App.config file. I've written the value explicitly here for demo purposes. 
    var filePath = "C:\\Logs"; 

    // Append a backslash if one is not present at the end of the file path. 
    if (!filePath.EndsWith("\\")) 
    { 
     filePath += "\\"; 
    } 

    // Create the path if it doesn't exist. 
    if (!Directory.Exists(filePath)) 
    { 
     Directory.CreateDirectory(filePath); 
    } 

    // Create the file name with a calendar sortable date on the end. 
    var now = DateTime.Now; 
    filePath += string.Format("Daily Log [{0}-{1}-{2}].txt", now.Year, now.Month, now.Day); 

    // Check if the file that is about to be created already exists. If so, append a number to the end. 
    if (File.Exists(filePath)) 
    { 
     var counter = 1; 
     filePath = filePath.Replace(".txt", " (" + counter + ").txt"); 
     while (File.Exists(filePath)) 
     { 
      filePath = filePath.Replace("(" + counter + ").txt", "(" + (counter + 1) + ").txt"); 
      counter++; 
     } 
    } 

    // Note that after the file is created, the file stream is still open. It needs to be closed 
    // once it is created if other methods need to access it. 
    using (var file = File.Create(filePath)) 
    { 
     file.Close(); 
    } 
} 
-1

試試這個:它在任何情況下工作,如果文件不存在,它會創建它,然後寫入它。如果已經存在,沒有問題它會打開和寫入:

using (FileStream fs= new FileStream(@"File.txt",FileMode.Create,FileAccess.ReadWrite)) 
{ 
    fs.close(); 
} 
using (StreamWriter sw = new StreamWriter(@"File.txt")) 
{ 
    sw.WriteLine("bla bla bla"); 
    sw.Close(); 
} 
+1

使用將通過調用關閉文件配置。在你的示例文件被關閉兩次 – 2016-09-20 04:24:40

13
FileStream fs= File.Create(ConfigurationManager.AppSettings["file"]); 
fs.Close(); 
+5

歡迎來到Stackoverflow。你至少應該寫簡短的描述來描述你的答案/解決方案。 – 2014-03-17 19:24:32

+0

這是唯一的工作! <3 – 2016-09-22 12:19:01

0

我知道這是一個老問題,但我只是想扔了這一點那裏,你仍然可以使用File.Create("filename")",只是將.Dispose()添加到它。

File.Create("filename").Dispose();

這種方式創建並關閉在接下來的過程中使用它的文件。

相關問題