File being used by another process after using File.Create()

C#File Io

C# Problem Overview


I'm trying to detect if a file exists at runtime, if not, create it. However I'm getting this error when I try to write to it: >The process cannot access the file 'myfile.ext' because it is being used by another process.

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 
}

Any ideas on how to fix it?

C# Solutions


Solution 1 - C#

    File.Create(FilePath).Close();
    File.WriteAllText(FileText);

I want to update this answer to say that this is not really the most efficient way to write all text. You should only use this code if you need something quick and dirty.

I was a young programmer when I answered this question, and back then I thought I was some kind of genius for coming up with this answer.

Solution 2 - C#

The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:

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

The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.

Solution 3 - C#

When creating a text file you can use the following code:

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

Using the code from your comment. The file(stream) you created must be closed. File.Create return the filestream to the just created file.:

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 
}

Solution 4 - C#

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

Solution 5 - C#

File.Create returns a FileStream. You need to close that when you have written to the file:

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);
        }

You can use using for automatically closing the file.

Solution 6 - C#

I updated your question with the code snippet. After proper indenting, it is immediately clear what the problem is: you use File.Create() but don't close the FileStream that it returns.

Doing it that way is unnecessary, StreamWriter already allows appending to an existing file and creating a new file if it doesn't yet exist. Like this:

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

Which uses this StreamWriter constructor.

Solution 7 - C#

I know this is an old question, but I just want to throw this out there that you can still use File.Create("filename")", just add .Dispose() to it.

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

This way it creates and closes the file for the next process to use it.

Solution 8 - C#

This question has already been answered, but here is a real world solution that checks if the directory exists and adds a number to the end if the text file exists. I use this for creating daily log files on a Windows service I wrote. I hope this helps someone.

// 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();
	}
}

Solution 9 - C#

I think I know the reason for this exception. You might be running this code snippet in multiple threads.

Solution 10 - C#

Try this: It works in any case, if the file doesn't exists, it will create it and then write to it. And if already exists, no problem it will open and write to it :

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(); 
 } 
 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrettView Question on Stackoverflow
Solution 1 - C#Carsen Daniel YatesView Answer on Stackoverflow
Solution 2 - C#Chris DunawayView Answer on Stackoverflow
Solution 3 - C#Ralf de KleineView Answer on Stackoverflow
Solution 4 - C#user3430377View Answer on Stackoverflow
Solution 5 - C#kimtiedeView Answer on Stackoverflow
Solution 6 - C#Hans PassantView Answer on Stackoverflow
Solution 7 - C#IamBatmanView Answer on Stackoverflow
Solution 8 - C#HalcyonView Answer on Stackoverflow
Solution 9 - C#Kusala SubasingheView Answer on Stackoverflow
Solution 10 - C#gyousefiView Answer on Stackoverflow