如何锁定在C#文件? [英] How to lock a file with C#?

查看:317
本文介绍了如何锁定在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:\Users\Juan Luis\Desktop\corte.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆