C# 如何锁定文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1432050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to lock file
提问by Naruto
please tell me how to lock file in c#
请告诉我如何在c#中锁定文件
Thanks
谢谢
采纳答案by Mitch Wheat
Simply open it exclusively:
只需单独打开它:
using (FileStream fs =
File.Open("MyFile.txt", FileMode.Open, FileAccess.Read, FileShare.None))
{
// use fs
}
Ref.
参考。
Update: In response to comment from poster: According to the online MSDN doco, File.Open is supported in .Net Compact Framework 1.0 and 2.0.
更新:回应来自海报的评论:根据在线MSDN doco,.Net Compact Framework 1.0 和 2.0 支持 File.Open。
回答by David Refaeli
FileShare.None would throw a "System.IO.IOException" error if another thread is trying to access the file.
如果另一个线程试图访问该文件,FileShare.None 将抛出“System.IO.IOException”错误。
You could use some function using try/catch to wait for the file to be released. Example here.
您可以使用 try/catch 使用一些函数来等待文件被释放。示例在这里。
Or you could use a lock statement with some "dummy" variable before accessing the write function:
或者您可以在访问 write 函数之前使用带有一些“虚拟”变量的 lock 语句:
// The Dummy Lock
public static List<int> DummyLock = new List<int>();
static void Main(string[] args)
{
MultipleFileWriting();
Console.ReadLine();
}
// Create two threads
private static void MultipleFileWriting()
{
BackgroundWorker thread1 = new BackgroundWorker();
BackgroundWorker thread2 = new BackgroundWorker();
thread1.DoWork += Thread1_DoWork;
thread2.DoWork += Thread2_DoWork;
thread1.RunWorkerAsync();
thread2.RunWorkerAsync();
}
// Thread 1 writes to file (and also to console)
private static void Thread1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 20; i++)
{
lock (DummyLock)
{
Console.WriteLine(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + " - 3");
AddLog(1);
}
}
}
// Thread 2 writes to file (and also to console)
private static void Thread2_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 20; i++)
{
lock (DummyLock)
{
Console.WriteLine(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + " - 4");
AddLog(2);
}
}
}
private static void AddLog(int num)
{
string logFile = Path.Combine(Environment.CurrentDirectory, "Log.txt");
string timestamp = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss");
using (FileStream fs = new FileStream(logFile, FileMode.Append,
FileAccess.Write, FileShare.None))
{
using (StreamWriter sr = new StreamWriter(fs))
{
sr.WriteLine(timestamp + ": " + num);
}
}
}
You can also use the "lock" statement in the actual writing function itself (i.e. inside AddLog) instead of in the background worker's functions.
您还可以在实际写入函数本身(即在 AddLog 中)而不是在后台工作程序的函数中使用“lock”语句。