C#以独占模式打开文件 [英] open file in exclusive mode in C#

查看:31
本文介绍了C#以独占模式打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以独占模式打开一个文件进行读取,如果文件已经被其他进程/线程打开,我想收到一个异常.我尝试了以下代码,但不起作用,即使我打开了 foo.txt,我仍然可以访问 Console.WriteLine 语句.有什么想法吗?

I want to open a file for read in exclusive mode, and if the file is already opened by some process/thread else, I want to receive an exception. I tried the following code, but not working, even if I opened the foo.txt, I still can reach the Console.WriteLine statement. Any ideas?

static void Main(string[] args)
{
    using (Stream iStream = File.Open("c:\software\code.txt", FileMode.Open,
    FileAccess.Read, FileShare.None))
    {
        Console.WriteLine ("I am here");
    }

    return;
}

推荐答案

你正在做的事情是正确的.可能您只是在错误地测试它.您应该使用在打开时锁定文件的程序打开它.记事本不行.您可以运行您的应用程序两次以查看:

What you are doing is the right thing. Probably you are just testing it incorrectly. You should open it with a program that locks the file when it's open. Notepad wouldn't do. You can run your application twice to see:

static void Main(string[] args)
{
    // Make sure test.txt exists before running. Run this app twice to see.
    File.Open("test.txt", FileMode.Open, FileAccess.Read, FileShare.None);
    Console.ReadKey();
}

这篇关于C#以独占模式打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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