开发者

Program crashes after trying to use a recently created file. C#

So here is my code

if (!File.Exists(pa开发者_StackOverflow中文版thName))
{
    File.Create(pathName);
}
StreamWriter outputFile = new StreamWriter(pathName,true);

But whenever I run the program the first time the path with file gets created. However once I get to the StreamWriter line my program crashes because it says my fie is in use by another process. Is there something I'm missing between the File.Create and the StreamWriter statements?


File.Create doesn't just create the file -- it also opens it for reading and writing. So the file is indeed already in use when you try to create the StreamWriter: by your own process.

StreamWriter will create the file specified by pathName if it doesn't exist, so you can simply remove the File.Exists check and simplify your your code this:

using (var writer = new StreamWriter(pathName, true))
{
   // ...
}

From MSDN:

StreamWriter Constructor (Stream)

Initializes a new instance of the StreamWriter class for the specified file [...]. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.


As others have mentioned, File.Create is creating a FileWriter that's holding your file open. But aside from that, there's no reason to check for file existence before trying to open the file. Just tell File.Open to open an existing file if one is there:

var outputFile = new StreamWriter(File.Open(pathName, FileMode.OpenOrCreate));


After the File.Create the stream is still open.

You could use:

File.Create(pathName).Close();

This creates the file and closes it directly.

More accepted is:

using (var file = File.Create(pathName)) {
   // use the file here
   // it will be closed when leaving the using block
}

Also: Why do you create a file, that you create 2 lines further in your code? The StreamWriter constructor (with append=true) will create or append the file if it does not exist.


File.Create returns a FileStream. Why don't you save that and pass it to the StreamWriter constructor instead of passing a pathname?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜