我不是一个非常有经验的程序员,所以我想知道我的解决方案是好的还是有更简单的方法。你能给我一些反馈吗?
问题:
我有多个C#程序正在修改网络中的计算机上的文本文件。我需要每个程序以这样的方式打开文件:如果程序试图在文件已经在另一个程序中打开时打开文件,它将等到文件关闭。
我的解决方案:
public void MainFunction(machineName, fileName, timeOut){ //Start here
filePath = "\\\\" + machineName + "\\Users\\Public\\" + fileName + ".txt";
FileStream file = GetFile(filePath, timeOut); // See below
ModifyFile(file) //This function is unique to every program
file.Close();
return;
}
// Block the program until the file opens or you reach the timeout limit
public FileStream GetFile(string fileName, int timeOut){ // Recursive function
FileStream file = null;
try{
file = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
return file; // Success!
}catch (IOException ex){ // File was already open
if (timeOut > 0){
System.Threading.Thread.Sleep(1);
file = GetFile(fileName, (timeOut - 1)); // Recursively call this function
}
if (file != null){ // Got file before timeout
return file;
}else{ // Timeout
throw ex;
}
}catch (Exception ex){ // Something else went wrong
throw ex;
}
}