简体   繁体   中英

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:

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. 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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM