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

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

问题描述

我想打开独占模式读取一个文件,如果文件已经被一些进程/线程的人打开,我想收到异常。我尝试以下code,但没有工作,即使我打开foo.txt的,我仍然可以达到Console.WriteLine命令语句。任何想法?

 静态无效的主要(字串[] args)
{
    使用(流的IStream = File.Open(C:\\\\ SOFTWARE \\\\ code.txt,FileMode.Open,
    FileAccess.Read,FileShare.None))
    {
        Console.WriteLine(我在这里);
    }    返回;
}


解决方案

你在做什么是正确的事情。也许你只是测试它不正确。你应该用程序打开它锁定该文件时它是开放。记事本不会做。你可以运行你的应用程序两次看到:

 静态无效的主要(字串[] args)
{
    //确保test.txt的运行前存在。运行这个程序两次看到的。
    File.Open(test.txt的FileMode.Open,FileAccess.Read,FileShare.None);
    Console.ReadKey();
}

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天全站免登陆