如何使用.NET打开文件以进行非排他性写访问 [英] How to open a file for non-exclusive write access using .NET

查看:57
本文介绍了如何使用.NET打开文件以进行非排他性写访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在具有非独占写访问权限的.NET中打开文件?如果是这样,怎么办?我希望有两个或多个进程同时写入同一文件.

Is it possible to open a file in .NET with non exclusive write access? If so, how? My hope is to have two or more processes write to the same file at the same time.

:这是此问题的上下文:我正在为IIS写一个简单的日志记录HTTPModule.由于在不同应用程序池中运行的应用程序作为不同的进程运行,因此我需要一种在进程之间共享日志文件的方法.我可以编写一个复杂的文件锁定例程,也可以编写一个懒惰的编写器,但这是一个废弃项目,因此并不重要.

Here is the context of this question: I am writing a simple logging HTTPModule for IIS. Since applications running in different app pools run as distinct processes, I need a way to share the log file between processes. I could write a complex file locking routine, or a lazy writer, but this is a throw away project so its not important.

这是我用来弄清楚该过程的测试代码.

This is the test code I used to figure out the process.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;

namespace FileOpenTest
{
    class Program
    {
        private static bool keepGoing = true;

        static void Main(string[] args)
        {
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);

            Console.Write("Enter name: ");
            string name = Console.ReadLine();
            //Open the file in a shared write mode
            FileStream fs = new FileStream("file.txt", 
                                           FileMode.OpenOrCreate, 
                                           FileAccess.ReadWrite, 
                                           FileShare.ReadWrite);

            while (keepGoing)
            {
                AlmostGuaranteedAppend(name, fs);
                Console.WriteLine(name);
                Thread.Sleep(1000);
            }

            fs.Close();
            fs.Dispose();
        }

        private static void AlmostGuaranteedAppend(string stringToWrite, FileStream fs)
        {
            StreamWriter sw = new StreamWriter(fs);

            //Force the file pointer to re-seek the end of the file.
            //THIS IS THE KEY TO KEEPING MULTIPLE PROCESSES FROM STOMPING
            //EACH OTHER WHEN WRITING TO A SHARED FILE.
            fs.Position = fs.Length;

            //Note: there is a possible race condition between the above
            //and below lines of code. If a context switch happens right
            //here and the next process writes to the end of the common
            //file, then fs.Position will no longer point to the end of
            //the file and the next write will overwrite existing data.
            //For writing periodic logs where the chance of collision is
            //small, this should work.

            sw.WriteLine(stringToWrite);
            sw.Flush();
        }

        private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
        {
            keepGoing = false;
        }
    }
}

推荐答案

使用 FileShare 枚举.具体来说,请使用FileShare.ReadWrite.

Use the FileShare enumeration when opening the file using File.Open. Specifically, use FileShare.ReadWrite.

这篇关于如何使用.NET打开文件以进行非排他性写访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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