繁体   English   中英

C#File。使用FileMode.Create打开一个只读文件

[英]C# File.Open a read-only file with FileMode.Create

我想要做的是覆盖只读文件。 带有读/写文件。

如果我使用File.Open(file, FileMode.Create)读取/写入文件File.Open(file, FileMode.Create)那么如果文件存在则删除它并创建一个新文件。 (虽然我怀疑如果它存在,那么它只是打开文件并删除内容,这就是为什么它无法处理它作为读/写遇到的文件)。

我尝试了不同的FileAccess枚举,但它们似乎都没有帮助我(我一直得到一个UnauthorizedAccessException )。

解决方法是我在尝试File.Open并创建一个新文件之前将文件设置为读/写,这是唯一的方法吗?

谢谢

考虑ReadOnly的目的。 这是为了停止对文件的更改。 你要做的是改变文件(在这种情况下通过覆盖它)。

我想你需要做的是设置文件属性:

File.SetAttributes(filePath, FileAttributes.Normal);

在您写入文件之前。

是的,这是一种设计行为。 您无法写入只读文件,因此您也无法覆盖它。

因此,唯一且完全有效的选项是首先删除ReadOnly标志。

使用FileInfo从ReadOnly更改文件的属性(如果您有权限),然后覆盖该文件。

是的,您需要在写入之前删除readonly属性。 这里有一些文件工具来检测文件是否只读,然后设置非只读属性。

    public static bool IsReadOnly(string file)
    {
        return (File.GetAttributes(file) & FileAttributes.ReadOnly) ==
                FileAttributes.ReadOnly;
    }

    public static void SetNonReadOnlyAttributes(string file)
    {
        try
        {
            FileAttributes attrs = File.GetAttributes(file);
            File.SetAttributes(file, attrs & ~FileAttributes.ReadOnly);
        }
        catch (Exception ex)
        {
            throw new Exception(
                string.Format(
                    "Error setting non-readonly attributes to file {0}: {1}",
                    file, ex.Message));
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM