如何使用 C# 锁定文件? [英] How to lock a file with C#?
问题描述
我不确定人们通常所说的锁定"文件是什么意思,但我想要的是对一个文件做那件事,当我尝试打开时会产生指定的文件正在使用"错误消息它与另一个应用程序.
I'm not sure what people usually mean by "lock" a file, but what I want is to do that thing to a file that will produce a "The specified file is in use" error message when I try to open it with another application.
我想这样做是为了测试我的应用程序,以查看当我尝试打开处于此状态的文件时它的行为.我试过这个:
I want to do this to test my application to see how it behaves when I try to open a file that is on this state. I tried this:
FileStream fs = null;
private void lockToolStripMenuItem_Click(object sender, EventArgs e)
{
fs = new FileStream(@"C:UsersJuan LuisDesktopcorte.txt", FileMode.Open);
}
private void unlockToolStripMenuItem_Click(object sender, EventArgs e)
{
fs.Close();
}
但显然它没有达到我的预期,因为我能够在锁定"文件时用记事本打开它.那么,我如何才能锁定文件,使其无法使用其他应用程序打开以进行测试?
But apparently it didn't do what I expected because I was able to open the file with Notepad while it was "locked". So how can I lock a file so it cannot be opened with another application for my testing purposes?
推荐答案
根据 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);
这篇关于如何使用 C# 锁定文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!