FileStream 可以从只读提升为读写吗?

发布于 2024-09-11 03:56:25 字数 61 浏览 0 评论 0原文

有没有办法将只读文件流提升为读写?我正在寻找类似于 Win32 SDK 函数 ReOpenFile 的功能。

Is there a way to promoting a Read-Only FileStream to Read-Write? I am looking for functionality similar to the Win32 SDK function ReOpenFile.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烦人精 2024-09-18 03:56:25

干得好。使用了一点 pInvoke Interop 的优点(缺点),但它可以做到。我为访问和共享模式参数省略并添加了一些神奇的常量,因此请随意封装它们。

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);

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);
蔚蓝源自深海 2024-09-18 03:56:25

你不能。

为什么首先要以只读方式打开它?为什么不直接打开一个新的文件流呢?如果 FileShare 设置正确,您甚至不必关闭旧的共享。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文