Reputation: 1001
I am using C# in Microsoft Visual Studio 2012, I am working on the following code:
string source = "d:\\source.txt";
string newFile = "d:\\newFile.txt";
if(!File.Exists(newFile))
{
File.Create(newFile);
string content = File.ReadAllText(source);
File.AppendAllText(newFile,content);
}
This code successfully creates the File but when it compiles the File.AppendAllText(newFile,content)
it generates the error:
the process cannot access the file "d:\newFile.txt" because it is being used by another process.
Why would this be?
Upvotes: 0
Views: 88
Reputation: 63065
you don't need to create file , AppendAllText
create if not exist, you get exception because File.Create return open file stream and then you try to access same file again. you need to properly close that stream before access the same file.
string source = "d:\\source.txt";
string newFile = "d:\\newFile.txt";
if(!File.Exists(newFile))
{
File.AppendAllText(newFile,File.ReadAllText(source););
}
File.AppendAllText:
Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.
but you can simply do your task by one line
File.Copy(source , newFile , false);
Upvotes: 0
Reputation: 754585
The File.Create
method returns a FileStream
object. This is holding the file open for write. Until that object is closed the file cannot be written to. The best way to fix this is to simply close the returned file
File.Create(newFile).Close();
This code is essentially copying the contents of an existing file to a new one. There is already an API available that does exactly that: File.Copy
. Your code could be simplified to the following
try {
File.Copy(source, newFile);
} catch (Exception) {
// File already exists or write can't occur
}
Upvotes: 6