开发者

File.Copy with opened stream not crashing. Know why?

开发者 https://www.devze.com 2022-12-23 18:38 出处:网络
I have this code, I open a stream (without closing or disposing it), then I copy the file used by the stream, I thought I should get a开发者_如何学Go \"Process can\'t access file somefile.xml because

I have this code, I open a stream (without closing or disposing it), then I copy the file used by the stream, I thought I should get a开发者_如何学Go "Process can't access file somefile.xml because it's being used by another process" exception, but I don't. Any idea why? Thanks! The code:

StreamWriter writer = new StreamWriter("C:\\somefile.xml");

writer.Write(string.Empty);

// I thought this should crash since a stream is using "C:\somefile.xml"
File.Copy("C:\\somefile.xml", "C:\\copy of somefile.xml", true);


It's because StreamWriter uses FileStream object and the default FileShare on the FileStream contructor which doesn't specify a explicit fileshare is FileShare.Read.

Allows subsequent opening of the file for reading. If this flag is not specified, any request to open the file for reading (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.

You can override that by using FileStream constructor that allows specifying the FileShare then passing that to the StreamWriter constructor.


Files can be locked for editing or locked for reading, or both. You just need to read a file to copy it and just opening a file does not automatically lock it for reading. You'll get the picture a little better if you read about how the underlying win32 api deals with file locks, here is a good place to start: LockFileEx Function.


I think it can depends on how the source file is opened. I mean if it has shared read.

0

精彩评论

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