[英]File locked only if copy/paste, not if cut/paste
I'm monitoring a folder for new files, and when the new file is present I read (and save in a txt) the file as following: 我正在监视文件夹中是否有新文件,并且当存在新文件时,我按以下方式读取(并保存为txt):
FileStream file = File.Open(this.filePath, FileMode.Open, FileAccess.Read);
StreamReader reader = new System.IO.StreamReader(file);
string text = reader.ReadToEnd();
reader.Close();
If I copy/paste in the folder the source file, I receive an IOExcpetion that tells me that the file is used by another process. 如果我将源文件复制/粘贴到文件夹中,则会收到一个IOExcpetion,它告诉我该文件已被另一个进程使用。 If I cut/paste in the folder, all works.
如果我剪切/粘贴到文件夹中,则一切正常。 Moreover locking problem happens also If I copy (but also cut in this case)/paste the file from another machine into the monitored folder.
此外,如果我将文件从另一台计算机复制(也要剪切)/粘贴到受监视的文件夹中,也会发生锁定问题。
Do you have an idea about what is happening? 您对发生的事情有想法吗?
There is a safer way to access to the file in order to avoid this type of locks? 有一种更安全的方法来访问文件以避免这种类型的锁?
Thanks! 谢谢!
Here is a little snippet I do to ensure the file is finished copying or not in use by another process. 这是我要确保文件已完成复制或不被其他进程使用的小片段。
private bool FileUploadCompleted(string filename)
{
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Open,
FileAccess.Read,
FileShare.None))
{
return true;
}
}
catch (IOException)
{
return false;
}
}
Then you can implement this before your process logic 然后可以在流程逻辑之前实现
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.