[英]Read and Write to File at the same time
對於使用File作為某種公司設備預留的全局存儲的應用程序,我需要一種方法來讀取和寫入文件(或鎖定文件,從中讀取,寫入並解鎖)。 一個小代碼片段將拍攝我的意思:
FileStream in = new FileStream("storage.bin", FileMode.Open);
//read the file
in.Close();
//!!!!!
//here is the critical section since between reading and writing, there shouldnt
//be a way for another process to access and lock the file, but there is the chance
//because the in stream is closed
//!!!!!
FileStream out = new FileStream("storage.bin", FileMode.Create);
//write data to file
out.Close();
這應該是這樣的
LockFile("storage.bin");
//read from it...
//OVERwrite it....
UnlockFile("storage.bin");
該方法應該是絕對安全的,因為程序應該同時在2000個設備上運行
僅使用獨占(非共享)訪問打開FileStream
將阻止其他進程訪問該文件。 這是打開文件進行讀/寫訪問時的默認設置。
您可以通過截斷它來“覆蓋”當前保持打開的文件。
所以:
using (var file = File.Open("storage.bin", FileMode.Open))
{
// read from the file
file.SetLength(0); // truncate the file
// write to the file
}
該方法應該是絕對安全的,因為程序應該同時在2000個設備上運行
根據您寫入文件的頻率,這可能會成為一個阻塞點。 您可能希望對此進行測試,以了解它的可擴展性。
此外,如果其中一個進程嘗試與另一個進程同時對該文件進行操作,則將拋出IOException
。 實際上沒有辦法在文件上“等待”,因此您可能希望以更有序的方式協調文件訪問。
您需要一個單獨的流,為讀取和寫入打開。
FileStream fileStream = new FileStream(
@"c:\words.txt", FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None);
或者你也可以嘗試
static void Main(string[] args)
{
var text = File.ReadAllText(@"C:\words.txt");
File.WriteAllText(@"C:\words.txt", text + "DERP");
}
根據http://msdn.microsoft.com/en-us/library/system.io.fileshare(v=vs.71).aspx
FileStream s2 = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.None);
您需要傳入FileShare枚舉值None以在FileStream構造函數重載上打開:
fs = new FileStream(@"C:\Users\Juan Luis\Desktop\corte.txt", FileMode.Open,
FileAccess.ReadWrite, FileShare.None);
您可能正在尋找FileStream.Lock和FileStream.Unlock
我認為你只需要在重載的Open方法中使用FileShare.None標志。
file = File.Open("storage.bin", FileMode.Open, FileShare.None);
我最后編寫了這個幫助程序類來執行此操作:
public static class FileHelper
{
public static void ReplaceFileContents(string fileName, Func<String, string> replacementFunction)
{
using (FileStream fileStream = new FileStream(
fileName, FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None))
{
StreamReader streamReader = new StreamReader(fileStream);
string currentContents = streamReader.ReadToEnd();
var newContents = replacementFunction(currentContents);
fileStream.SetLength(0);
StreamWriter writer = new StreamWriter(fileStream);
writer.Write(newContents);
writer.Close();
}
}
}
它允許您傳遞一個函數,該函數將獲取現有內容並生成新內容,並確保在發生此更改時,其他任何內容都不會讀取或修改該文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.