使用 FileStream 和这些选项 c# 读取文本文件的实际内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14134887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:47:16  来源:igfitidea点击:

Read the actual contents of text file using FileStream and these options c#

c#filestream

提问by user1776480

I need to open a text file within C# using FileStream and with the options mentioned below

我需要使用 FileStream 和下面提到的选项在 C# 中打开一个文本文件

var fileStream = new FileStream(filePath, 
                                FileMode.Open, 
                                FileAccess.Read, 
                                FileShare.Read, 64 * 1024,
                               (FileOptions)FILE_FLAG_NO_BUFFERING | 
                                  FileOptions.WriteThrough & FileOptions.SequentialScan);

The text file contains a "1" or "0" and after obtaining the results I am going to assign the contents of the text file to a string variable. In case you're interested, I need the above options in order to avoid Windows reading the text files from cache.

文本文件包含“1”或“0”,在获得结果后,我要将文本文件的内容分配给一个字符串变量。如果您有兴趣,我需要上述选项以避免 Windows 从缓存中读取文本文件。

System.IO.File.ReadAllText()

... is not good enough.

……不够好。

Would somebody be kind enough to write a simple sub which incorporates these requirements for me please as the examples I've seen so far involve working with bytes and buffers (an area I really need to work on at this time) and leaves it at that.

有人愿意写一个简单的子程序来为我合并这些要求吗,因为到目前为止我看到的示例涉及使用字节和缓冲区(我此时真正需要处理的区域)并将其留在那里.

Thanks

谢谢

回答by Hans Ke?ing

You can use a StreamReaderto read from the stream:

您可以使用StreamReader从流中读取:

string contents;
using(var sr = new StreamReader(fileStream))
{
   contents = sr.ReadToEnd();
}

回答by TheKingDave

Maybe something like:

也许是这样的:

    FileStream fileStream = new FileStream("[path]", FileMode.Open, FileAccess.Read, FileShare.Read, 64 * 1024,
        (FileOptions)0x20000000 | FileOptions.WriteThrough & FileOptions.SequentialScan);

    string fileContents;
    using (StreamReader reader = new StreamReader(fileStream))
    {
        fileContents = reader.ReadToEnd();
    }


    bool assignedvariable = Convert.ToBoolean(fileContents);

assignedvariable will hold true if the file contains 1 and false if it contains 0.

如果文件包含 1,assignedvariable 将为 true,如果文件包含 0,则为 false。

Sorry if this has been answered already people post very fast here.

对不起,如果这已经得到回答,人们在这里发帖速度非常快。

回答by Paul Zahra

File.ReadAllBytes

or

或者

File.ReadAllText

Will both theoretically use windows file cache.

理论上都将使用 Windows 文件缓存。

Read thisfor more understanding and for some of the restrictions on FILE_FLAG_NO_BUFFERING and also read this for a similar stackoverflow question

阅读此内容以了解更多信息以及对 FILE_FLAG_NO_BUFFERING 的一些限制,并阅读此内容以了解类似的计算器溢出问题

回答by Sau001

This is what I did to read an array of bytesusing FileStreamand it worked well. I have expanded the namespaces for the sake of technical clarity. You should chose the FileShareand FileAccessparameters as per your scenario.

这就是我使用FileStream读取字节数组时所做的,并且运行良好。为了技术上的清晰起见,我扩展了命名空间。您应该根据您的方案选择FileShareFileAccess参数。

    byte[] buffer = null;
    using (System.IO.FileStream stm = new System.IO.FileStream("c:\YourFile.txt", 
               System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None))
    {
    buffer = new byte[stm.Length];
    stm.Read(buffer, 0, Convert.ToInt32(stm.Length));
    }

How to read the contents of the file as a String and not an array of bytes?

如何将文件的内容作为字符串而不是字节数组读取?

 string buffer = null;
 using (System.IO.FileStream stm = new 
     System.IO.FileStream("c:\YourFile.txt",System.IO.FileMode.Open,  
     System.IO.FileAccess.Read, System.IO.FileShare.None))
     {
         using (System.IO.StreamReader rdr = new System.IO.StreamReader (stm))
         {
                        buffer=rdr.ReadToEnd();
         }
     }

Why is StreamReader better than converting the byte[] to string using the desired encoding?

为什么 StreamReader 比使用所需的编码将 byte[] 转换为字符串更好?

The StreamReader class is powerful because it will examine the header bytes and determine the encoding scheme for you. You do not have to use System.Text.Encoding.UTF8.GetString().

StreamReader 类功能强大,因为它会检查头字节并为您确定编码方案。您不必使用System.Text.Encoding.UTF8.GetString()

Why use FileStream and why not System.IO.File.ReadAllBytes/ReadAllText ?I wanted precise control on the file locking mechanism. In my scenario, I had a process that was polling a folder for incoming files. I wanted to be sure that when I read the file, the slow running process on the other end had completed its job and the file was ready for my process to read and analyze.

为什么使用 FileStream 而为什么不使用 System.IO.File.ReadAllBytes/ReadAllText ?我想要精确控制文件锁定机制。在我的场景中,我有一个进程轮询文件夹中的传入文件。我想确保当我读取文件时,另一端运行缓慢的进程已完成其工作,并且文件已准备好供我的进程读取和分析。

What are the drawbacks of reading the entire file as a single array of bytes?If you are going to read a very large file all at once then you are placing a higher demand on your RAM. Think of an application which renders movies. You have a 100MB movie file. You do not want to read the entire file at once. You would rather have it read in chunks of say 100KB at a time, render the scenes and then move on to the next chunk. This makes your application more scalable. Your movie application is now more scalable. You can handle very large movies wihout running into the risk of System.IO.OutOfMemoryException.

将整个文件作为单个字节数组读取的缺点是什么?如果您要一次读取一个非常大的文件,那么您对 ​​RAM 的要求会更高。想想一个渲染电影的应用程序。您有一个 100MB 的电影文件。您不想一次读取整个文件。您宁愿一次读取 100 KB 的数据块,渲染场景,然后移至下一个数据块。这使您的应用程序更具可扩展性。您的电影应用程序现在更具可扩展性。您可以处理非常大的电影而不会遇到 System.IO.OutOfMemoryException 的风险。