标签: streamreader

C#"使用"块

我有类似下面的代码...有人在这里提到WebClient,Stream和StreamReader对象都可以从使用块中受益.两个简单的问题:

1:这个小片段看起来如何使用块?我做自己的研究没有问题,所以资源链接很好但是看到一个例子会更快更容易,我会从中理解它.

2:我想养成良好的编码标准的习惯,如果我对使用积木更好的原因有所了解会有所帮助...是否只是让你不必担心关闭或在那里更多原因?谢谢!

WebClient client = new WebClient();
Stream stream = client.OpenRead(originGetterURL);
StreamReader reader = new StreamReader(stream);

JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine());
string encryptionKey = (string)jObject["key"];
string originURL = (string)jObject["origin_url"];

stream.Close()
reader.Close()
Run Code Online (Sandbox Code Playgroud)

c# design-patterns using stream streamreader

5
推荐指数
2
解决办法
1663
查看次数

如何在ShareDenyWrite模式下打开StreamReader?

如何打开一个StreamReaderFILE_SHARE_READ,FILE_SHARE_WRITE,FILE_SHARE_DELETE


同样的问题,略有扩展

我如何打开一个StreamReader以便我可以读取编码的文本文件,共享选项,以便另一个进程可以读取该文件?

我如何打开一个StreamReader以便我可以读取编码的文本文件,使用共享选项,以便其他进程可以在我阅读时修改该文件?

我如何打开一个StreamReader以便我可以读取编码的文本文件,使用共享选项,以便其他进程可以在我阅读时删除该文件?


同样的问题,稍微扩大一点

在.NET Framework类库中有一个名为的类StreamReader.它是唯一一个用于读取"text"的类,这就是它从抽象基TextReader类中下降的原因.在TextReader/StreamReader允许您指定由您试图打开该文件使用的编码,并可以为您的文件进行解码,并返回Strings文本.

一旦我打开了一个文件StreamReader:

var sr = new StreamReader(path);
Run Code Online (Sandbox Code Playgroud)

文件被锁定,其他进程无法修改删除该文件.我需要的是相当于一个FileStream类的FileShare枚举:

  • :拒绝共享当前文件.在文件关闭之前,任何打开文件的请求(通过此进程或其他进程)都将失败.
  • 读取 ":允许随后打开文件进行读取.如果未指定此标志,则打开文件进行读取(通过此进程或其他进程)的任何请求都将失败,直到文件关闭.但是,即使此标志为如果指定,则可能仍需要其他权限才能访问该文件.
  • 写入:允许随后打开文件进行写入.如果未指定此标志,则在文件关闭之前,任何打开文件以进行写入(通过此进程或其他进程)的请求都将失败.但是,即使指定了此标志,仍可能需要其他权限才能访问该文件.
  • ReadWrite:允许随后打开文件进行读写.如果未指定此标志,则在文件关闭之前,任何打开文件以进行读取或写入(通过此进程或其他进程)的请求都将失败.但是,即使指定了此标志,仍可能需要其他权限才能访问该文件.
  • 删除:允许后续删除文件.

除此之外,由于显而易见的原因,我不能使用FileStream- 必须使用a StreamReader.

我怎样才能打开一个StreamReaderFileShare.ReadWrite | FileShare.Delete

c# sharing fileshare streamreader textreader

5
推荐指数
2
解决办法
4583
查看次数

使用StreamReader进行内存泄漏(?)

我有一些非常大的文件,每个文件500MB++大小,包含整数值(实际上它有点复杂),我正在循环中读取这些文件并计算所有文件的最大值.由于某种原因,内存在处理期间不断增长,看起来GC从未释放内存,这是由之前的实例获得的lines.

我无法流式传输数据,必须使用GetFileLines每个文件.用以存储所需要的实际内存量lines的一个文件500MB,为什么我得到5GBRAM使用正在处理的10个文件后?最终它在15个文件后崩溃,内存不足异常.

计算:

   int max = int.MinValue;

   for (int i = 0; i < 10; i++)
   {
      IEnumerable<string> lines = Db.GetFileLines(i);

      max = Math.Max(max, lines.Max(t=>int.Parse(t)));
   }
Run Code Online (Sandbox Code Playgroud)

GetFileLines代码:

   public static List<string> GetFileLines(int i)
   {
      string path = GetPath(i);

      //
      List<string> lines = new List<string>();
      string line;

      using (StreamReader reader = File.OpenText(path))
      {
         while ((line = reader.ReadLine()) != null)
         {
            lines.Add(line);
         }

         reader.Close();
         reader.Dispose(); // should I bother? …
Run Code Online (Sandbox Code Playgroud)

c# streamreader

5
推荐指数
1
解决办法
3895
查看次数

获取Streamreader的长度

我如何获得a的长度StreamReader,因为我知道将不再写入任何内容。我以为也许可以将所有数据传递给a MemoryStream,该方法有一个称为的方法Length,但是我对如何将byte []附加到a感到困惑MemoryStream

private void Cmd(string command, string parameter, object stream)
        {

            StreamWriter writer = (StreamWriter)stream;
            StreamWriter input;
            StreamReader output;

            Process process = new Process();

            try
            {
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.FileName = "cmd";
                process.Start();

                input = process.StandardInput;
                output = process.StandardOutput;
                input.WriteLine(command + " " + parameter);
                input.WriteLine("exit");

                using (MemoryStream ms = new MemoryStream())
                {
                    int length = 1024;
                    char[] charbuffer = new char[length];
                    byte[] …
Run Code Online (Sandbox Code Playgroud)

c# memorystream streamreader

5
推荐指数
2
解决办法
2万
查看次数

通过json.net从流中反序列化多个对象

Greatings!我需要反序列化序列化为json的不同对象的文件.这是结果文件:

{
  "Number": 1,
  "Description": "Run version with strategy data",
  "Context": "NA"
}[
  {
    "N": 0.0,
    "T": 2.0,
    "Adc": [
      0.0,
      0.0,
      0.0,
      0.0,
      0.0,
      0.0,
      0.0
    ],
    "SpltFr": 2.0,
    "Acc": 1.0,
    "DAcc": 0.0,
    "Acc2": 1.0,
    "OscFr": 0.5,
    "Fltr": 0,
    "CmpEr": false,
    "ErrPck": 0,
    "IndxDiff": 0,
    "Pos": 0,
    "FastAcc": [],
    "GIndx": 0,
    "Indx": 0,
    "PcTime": "0001-01-01T00:00:00"
  },
  {
    "N": 1.0,
    "T": 2.0,
    "Adc": [
      0.0,
      0.0,
      0.0,
      0.0,
      0.0,
      0.0,
      0.0
    ],
    "SpltFr": 2.2999999523162842,
    "Acc": 1.0,
    "DAcc": 0.0,
    "Acc2": 1.0, …
Run Code Online (Sandbox Code Playgroud)

c# json streamreader json.net

5
推荐指数
1
解决办法
1万
查看次数

为什么我的信息流不可读?

这是我在这里有关从日志文件中删除胖文件的问题的后遗症。

我有以下代码:

private readonly FileStream _fileStream;
private readonly StreamWriter _streamWriter;

. . .

    const int MAX_LINES_DESIRED = 1000;

    string uriPath = GetExecutionFolder() + "\\Application.log";
    string localPath = new Uri(uriPath).LocalPath;
    if (!File.Exists(localPath))
    {
        File.Create(localPath);
    }
    _fileStream = File.OpenWrite(localPath);
    // First, remove the earliest lines from the file if it's grown too much
    StreamReader reader = new StreamReader(_fileStream);
    . . .
Run Code Online (Sandbox Code Playgroud)

在显示的最后一行失败:

System.ArgumentException was unhandled
  _HResult=-2147024809
  _message=Stream was not readable.
Run Code Online (Sandbox Code Playgroud)

为什么不可读?我以为可能是因为文件为空,但是我向其中添加了一行,并且仍然得到相同的err msg。

c# file-io uri filestream streamreader

5
推荐指数
1
解决办法
3985
查看次数

阅读C#百万行

我有一个很长的文本文件.所有行都具有相同的长度.我想在C#中读取百万行而没有先读取之前的999999行,否则程序会变得太慢.我能怎么做?

c# text row line streamreader

5
推荐指数
2
解决办法
388
查看次数

在C#中读写非常大的文本文件

我有一个非常大的文件,大小近2GB.我正在尝试编写一个进程来读取文件并在没有第一行的情况下将其写出来.我几乎只能一次读写一行,这需要永远.我可以打开它,删除第一行并在TextPad中保存得更快,尽管这仍然很慢.

我使用此代码来获取文件中的记录数:

private long getNumRows(string strFileName)
{
    long lngNumRows = 0;
    string strMsg;

    try
    {
        lngNumRows = 0;
        using (var strReader = File.OpenText(@strFileName))
        {
            while (strReader.ReadLine() != null)
            {
                lngNumRows++;
            }

            strReader.Close();
            strReader.Dispose();
        }
    }
    catch (Exception excExcept)
    {
        strMsg = "The File could not be read: ";
        strMsg += excExcept.Message;
        System.Windows.MessageBox.Show(strMsg);
        //Console.WriteLine("Thee was an error reading the file: ");
        //Console.WriteLine(excExcept.Message);

        //Console.ReadLine();
    }

    return lngNumRows;
}
Run Code Online (Sandbox Code Playgroud)

这只需要几秒钟就可以运行.当我添加以下代码时,它需要永远运行.难道我做错了什么?为什么写入会增加这么多时间?关于如何让它更快的任何想法?

private void ProcessTextFiles(string strFileName)
{
    string strDataLine;
    string strFullOutputFileName;
    string strSubFileName;
    int intPos; …
Run Code Online (Sandbox Code Playgroud)

.net c# wpf streamwriter streamreader

5
推荐指数
1
解决办法
4770
查看次数

C# - 将XML节点值设置为来自StreamReader结果的Stings

我正在使用API​​调用从Web服务器返回一些XML数据.XML数据采用以下格式:

<forismatic>
    <quote>
        <quoteText>The time you think you're missing, misses you too.</quoteText>               
        <quoteAuthor>Ymber Delecto</quoteAuthor>
        <senderName></senderName>
        <senderLink></senderLink>
        <quoteLink>http://forismatic.com/en/55ed9a13c0/</quoteLink>
    </quote>
</forismatic>
Run Code Online (Sandbox Code Playgroud)

我可以成功检索原始XML数据,我想将<quoteText><quoteAuthor>节点值添加到字符串但似乎无法执行此操作.我目前的代码:

    private void btnGetQuote_Click(object sender, EventArgs e)
    {
        WebRequest req = WebRequest.Create("http://api.forismatic.com/api/1.0/");                            
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";

        string reqString = "method=getQuote&key=457653&format=xml&lang=en";
        byte[] reqData = Encoding.UTF8.GetBytes(reqString);
        req.ContentLength = reqData.Length;

        using (Stream reqStream = req.GetRequestStream())
            reqStream.Write(reqData, 0, reqData.Length);

        using (WebResponse res = req.GetResponse())
        using (Stream resSteam = res.GetResponseStream())
        using (StreamReader sr = new StreamReader(resSteam))
        {
            string xmlData = …
Run Code Online (Sandbox Code Playgroud)

c# xml streamreader winforms

5
推荐指数
1
解决办法
362
查看次数

将StreamReader设置为开头时出现奇怪的问号

我正在写一份关于求职面试的课程.一切都正常,除了一件事.当我使用外部方法TotalLines(我有单独的StreamReader)时,它工作正常,但是当我在程序中计算一些totalLines时,我在第一个问题的开头就收到一个问号.所以它是这样的:

?你叫什么名字?

但是在我正在阅读的文本文件中,我只是 - 你叫什么名字?

我不知道为什么会这样.也许这是我的问题,我将StreamReader重新开始?我检查了我的编码,一切,但没有任何效果.谢谢你的帮助 :)

PotentialEmployee potentialEmployee = new PotentialEmployee();
using (StreamReader InterviewQuestions = new StreamReader(text, Encoding.Unicode))
{
    int totalLines = 0;
    while (InterviewQuestions.ReadLine() != null)
    {
        totalLines++;
    }
    InterviewQuestions.DiscardBufferedData();
    InterviewQuestions.BaseStream.Seek(0, SeekOrigin.Begin);

    for (int numberOfQuestions = 0; numberOfQuestions < totalLines; numberOfQuestions++)
    {
        string question = InterviewQuestions.ReadLine();
        Console.WriteLine(question);
        string response = Console.ReadLine();
        potentialEmployee.Responses.Add(question, response);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我在外部方法中进行TotalLines计算时,问号不会显示.有什么想法吗?

c# streamreader

5
推荐指数
1
解决办法
172
查看次数