C#:检查文件是否未锁定和可写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1175979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C#: Check if a file is not locked and writable
提问by
I want to check if a list of files is in use or not writable before I start replacing files. Sure I know that the time from the file-check and the file-copy there is a chance that one or more files is gonna to be locked by someone else but i handle those exceptions. I want to run this test before file copy because the complete list of files have a better chance to succeed than if a file in the middle of the operation fails to be replaced.
我想在开始替换文件之前检查文件列表是否正在使用或不可写。当然,我知道从文件检查和文件复制开始,一个或多个文件有可能被其他人锁定,但我会处理这些异常。我想在文件复制之前运行这个测试,因为完整的文件列表比操作中间的文件没有被替换有更大的成功机会。
Have any of you an example or a hint in the right direction
你们中的任何人都有正确方向的示例或提示
回答by maxwellb
Read one byte, write same byte?
读一个字节,写同一个字节?
回答by Lasse V. Karlsen
You must open each file for writing in order to test this.
您必须打开每个文件进行写入以进行测试。
回答by Dmitry Tashkinov
回答by Dmitry Tashkinov
There is no guarantee that the list you get, at any point of time, is going to stay the same the next second as somebody else might take control of the file by the time you come back to them.
无法保证您在任何时间点获得的列表会在下一秒保持不变,因为在您返回时其他人可能会控制该文件。
I see one way though - "LOCK" the files that you want to replace by getting their corresponding FileStream
objects. This way you are sure that you have locked all "available" files by opening them and then you can replace them the way you want.
我看到了一种方法 - 通过获取相应的FileStream
对象来“锁定”要替换的文件。通过这种方式,您可以确保通过打开所有“可用”文件来锁定它们,然后您可以按照自己的方式替换它们。
public void TestGivenFiles(List<string> listFiles)
{
List<FileStream> replaceAbleFileStreams = GetFileStreams(listFiles);
Console.WriteLine("files Received = " + replaceAbleFileStreams.Count);
foreach (FileStream fileStream in replaceAbleFileStreams)
{
// Replace the files the way you want to.
fileStream.Close();
}
}
public List<FileStream> GetFileStreams(List<string> listFilesToReplace)
{
List<FileStream> replaceableFiles = new List<FileStream>();
foreach (string sFileLocation in listFilesToReplace)
{
FileAttributes fileAttributes = File.GetAttributes(sFileLocation);
if ((fileAttributes & FileAttributes.ReadOnly) != FileAttributes.ReadOnly)
{ // Make sure that the file is NOT read-only
try
{
FileStream currentWriteableFile = File.OpenWrite(sFileLocation);
replaceableFiles.Add(currentWriteableFile);
}
catch
{
Console.WriteLine("Could not get Stream for '" + sFileLocation+ "'. Possibly in use");
}
}
}
return replaceableFiles;
}
That said, you are better off trying to replace them one by one and and ignore the ones that you can't.
也就是说,你最好尝试一个一个地替换它们,而忽略那些你不能替换的。