[英]File locked only if copy/paste, not if cut/paste
我正在监视文件夹中是否有新文件,并且当存在新文件时,我按以下方式读取(并保存为txt):
FileStream file = File.Open(this.filePath, FileMode.Open, FileAccess.Read);
StreamReader reader = new System.IO.StreamReader(file);
string text = reader.ReadToEnd();
reader.Close();
如果我将源文件复制/粘贴到文件夹中,则会收到一个IOExcpetion,它告诉我该文件已被另一个进程使用。 如果我剪切/粘贴到文件夹中,则一切正常。 此外,如果我将文件从另一台计算机复制(也要剪切)/粘贴到受监视的文件夹中,也会发生锁定问题。
您对发生的事情有想法吗?
有一种更安全的方法来访问文件以避免这种类型的锁?
谢谢!
这是我要确保文件已完成复制或不被其他进程使用的小片段。
private bool FileUploadCompleted(string filename)
{
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Open,
FileAccess.Read,
FileShare.None))
{
return true;
}
}
catch (IOException)
{
return false;
}
}
然后可以在流程逻辑之前实现
while (!FileUploadCompleted(filePath))
{
//if the file is in use it will enter here
//So you could sleep the thread here for a second or something to allow it some time
// Also you could add a retry count and if it goes past the allotted retries you
// can break the loop and send an email or log the file for manual processing or
// something like that
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.