开发者

c# overwriting/saving current file

开发者 https://www.devze.com 2023-04-10 11:40 出处:网络
I am doing editor in c#, windows forms. I wish to save \'new content\' of file in the same file (usual usage of \'save\' option) but I receive IOException,[ the process cannot access the file \' filen

I am doing editor in c#, windows forms. I wish to save 'new content' of file in the same file (usual usage of 'save' option) but I receive IOException, [ the process cannot access the file ' filename' because it is being used开发者_如何学Python by another process. I have method that writes to a NEW file and it works. How to use it to overwrite current file.

Edit: I am using binarywriter http://msdn.microsoft.com/en-us/library/atxb4f07.aspx


Chances are that when you loaded the file, you didn't close the FileStream or whatever you used to read it. Always use a using statement for your streams (and other types implementing IDisposable), and it shouldn't be a problem. (Of course if you actually have that file open in a separate application, that's a different problem entirely.)

So instead of:

// Bad code
StreamReader reader = File.OpenText("foo.txt");
string data = reader.ReadToEnd();
// Nothing is closing the reader here! It'll keep an open
// file handle until it happens to be finalized

You should use something more like:

string data;
using (TextReader reader = File.OpenText("foo.txt"))
{
    data = reader.ReadToEnd();
}
// Use data here - the handle will have been closed for you

Or ideally, use the methods in File which do it all for you:

string text = File.ReadAllText("foo.txt");


Check if you're closing stream to the file. If not then you're blocking yourself.


Assuming that you have correctly closed the stream you used to open and read the file initially, to create, append or fail depending of file existence you should use the FileMode parameter in FileStream constructor.

Everything depends on the way you open the FileStream, see here: FileStream Constructor (String, FileMode)

if you specify FileMode Create:

Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires FileIOPermissionAccess.Write. System.IO.FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException is thrown.

0

精彩评论

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

关注公众号