I have a function that is reading a file and adding some of the string in a list and returning this list. Because I wanted that nobody and nothing could change, delete or whatever the current file that I was reading I locked it. Everything was fine, I did it somehow like this:
public static List<string> Read(string myfile)
{
using (FileStream fs = File.Open(myfile, FileMode.Open, FileAccess.Read, FileShare.None))
{
//read lines, add string to a list
//return list
}
}
Thats fine. Now I have another function in another class that is doing stuff with the list and calling other functions and so on. Now sometimes I want to move the file that I was reading. And here is the problem: because Im now in a new function and the function Read(string myfile) is already processed, there is no more lock in the file.
//in another class
public static void DoStuff(/*somefile*/)
{
List<string> = Read(/*somefile*/);
//the file (somefile) is not more locked!
//do stuff
if (something)
Move(/*somefile*/) //could get an error, file maybe not more there or changed...
}
So another function/user could change the file, rename it, deleting it or whatever => Im not able to move this file. Or I will move the changed file, but I dont what that. If I would use threading, another thread with the same function could lock the file again and I could not move it.
Thats why I somehow need to lock this file for a longer time. Is there an easy way? Or do I have to replace my using (FileStream fs = File.Open(myfile, FileMode.Open, FileAccess.Read, FileShare.None) code? Any suggestions? thank you
If you want to keep the file locked for longer then you need to refactor your code so that the
Streamobject is kept around for longer – I would change theReadmethod to accept aFileStream, a little bit like thisThe problem you are going to have is that
File.Movemethod is going to fail as this file is already locked (by you, butFile.Movedoesn’t know that).Depending on what exactly it is you want to do it might be possible to work out a way of keeping the file locked while also “moving” the file, (for example if you know
somethingin advance you could open the file specifyingFileOptions.DeleteOnCloseand write a new file with the same contents in the desired destination), however this isn’t really the same as moving the file and so it all depends on what exactly it is you are trying to do.In general such things are almost always going to be more trouble than they are worth – you are better off just unlocking the file just before you move it and catching/ handling any exception that is thrown as a result of the move.