开发者

Can a FileStream be promoted from Read-Only to Read-Write?

Is there a way to promoting a Read-Only FileStream to Read-Write? I am looking for functionality similar to the Win32 SD开发者_高级运维K function ReOpenFile.


Here you go. Uses a bit of pInvoke Interop goodness (badness), but it'll do it. I've skimped and threw in some magic constants for the access and sharemode parameters, so feel free to encapsulate that.

private static void Main()
{
    using (FileStream fs = new FileStream(@"..\..\Program.cs", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        using (TextReader tr = new StreamReader(fs))
        {
            Console.WriteLine(tr.ReadToEnd());

            using (FileStream fs1 = new FileStream(ReOpenFile(fs.SafeFileHandle, 3, 3, 0), FileAccess.ReadWrite))
            {
                fs1.Seek(0, SeekOrigin.End);
                using (TextWriter tw = new StreamWriter(fs1))
                {
                    tw.WriteLine("/* this should be all right */");
                }
            }
        }
    }
}

[DllImport("kernel32", SetLastError = true)]
private static extern SafeFileHandle ReOpenFile(SafeFileHandle hOriginalFile, uint dwAccess, uint dwShareMode, uint dwFlags);


You can't.

Why do you open it readonly in the first place? Why don't you just open a new FileStream? You do not even have to close the old one, provided that the FileShare is set correctly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜