简体   繁体   English

如何以只读模式打开文本文件,这意味着我无法执行写操作?

[英]How to open a text file in read-only mode means there i can not perform write?

I am trying it too much time but can not achieve the goal. 我尝试了太多时间,但无法实现目标。 File is opened but its opened in write mode. 文件已打开,但以写模式打开。

Code- in txtpath.text, I am passing the path of the text: 在txtpath.text中编码,我正在传递文本的路径:

System.IO.FileInfo fileObj= new System.IO.FileInfo(txtPath.Text);

fileObj.Attributes = System.IO.FileAttributes.ReadOnly;

System.Diagnostics.Process.Start(fileObj.FullName);

use the File.OpenRead method 使用File.OpenRead方法

 string sFilename = "myfile.txt";
 FileStream SR = File.OpenRead(sFilename);

Opening a file to only read it's contents: 打开文件仅读取其内容:

    // Open the stream and read it back.
    using (FileStream fs = File.OpenRead(path)) 
    {
        byte[] b = new byte[1024];
        UTF8Encoding temp = new UTF8Encoding(true);

        while (fs.Read(b,0,b.Length) > 0) 
        {
            Console.WriteLine(temp.GetString(b));
        }
    }

More about File.OpenRead : http://msdn.microsoft.com/en-us/library/system.io.file.openread.aspx 有关File.OpenRead更多信息: http : //msdn.microsoft.com/zh-cn/library/system.io.file.openread.aspx

Setting a file's ReadOnly attribute and executing it: 设置文件的ReadOnly属性并执行:

File.SetAttributes(txtPath.Text, File.GetAttributes(txtPath.Text) | FileAttributes.ReadOnly);
System.Diagnostics.Process.Start(txtPath.Text);

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

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