重新创建一个逗号分隔的文件而没有逗号 [英] Recreate a comma delimited file without the commas

查看:61
本文介绍了重新创建一个逗号分隔的文件而没有逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我是C#的新手,正在尝试将逗号分隔的文件读入fileStream,将逗号替换为空格,然后将fileStream输出到新文件中.但是,当我使用此代码时,输​​出似乎已编码.有什么想法我想念的吗?任何人都可以建议一种更简单的方法,因为我说我是该语言的新手:

Hey all,

I''m totally new to C# and am trying to read a comma delimited file into a fileStream, replace the commas with spaces and output the fileStream into a new file. When I use this code however the output seems to be encoded. Any ideas what I''m missing? Can anyone suggest an easier way of doing this, as I say I''m a total newbie to the language:

private void Read_File(object Sender, EventArgs e)
{
     FileStream fileStream = new FileStream("C:\\commas.txt", FileMode.Open);
     String data = "";
     String data2 = "";
     byte[] bytes = new byte[fileStream.Length];
     try
     {
          using (var sr = new StreamReader(fileStream, Encoding.Unicode)) 
         { 
             data = sr.ReadToEnd(); 
         }
         for (int i = 0; i < data.Length; i++)
         {
             if (data.ElementAt(i).Equals(","))
             {
                 data2 = data2 + " ";
             }
             else
             {
                 data2 = data2 + data.ElementAt(i);
             }
          }
          File.WriteAllText("C:\\nocommas.txt", data2); 
      }
      finally
      {
          fileStream.Close();
      }
  }



任何帮助将不胜感激.

Stephen.



Any help would be greatly appreciated.

Stephen.

推荐答案

由于您正在使用纯文本"内容,因此可以改用TextReader和TextWriter.那将是简单的方法.您也可以只使用简单的yourCurrentLine.Replace(",", " ")调用来执行转换.
如果文件确实很大,请使用ReadLine方法,如果保证文件长度合理,则可以使用ReadToEnd方法.
TextWriter的MSDN文档 [
Since you are working with Plain Text stuff, you could use a TextReader and TextWriter instead. That would be the simple way. You can also just use a simple yourCurrentLine.Replace(",", " ") call to perform the conversion.
If your file is really large, use the ReadLine approach, if the file is guaranteed to be of a reasonable length, then you can use the ReadToEnd approach.
MSDN Documentation for TextWriter[^]


您可以执行它与以下代码:
You can do it with this code:
private void Read_File(object Sender, EventArgs e)
{
  string contentOfFileWithCommas = File.ReadAllText("C:\\commas.txt",Encoding.UTF8);
  string contentOfFileWithoutCommas = contentOfFileWithCommas.Replace(",", " ");
  File.WriteAllText("C:\\nocommas.txt",contentOfFileWithoutCommas,Encoding.UTF8);
}


希望对您有所帮助.


Hope this helps.


非常感谢Marcus和ProgramFOX.我知道我觉得这太简单了,这让我变得太复杂了.再次感谢.

斯蒂芬.
Thanks very much Marcus and ProgramFOX. I knew I was overcomplicating this as it seems such a simple concept. Thanks again.

Stephen.


这篇关于重新创建一个逗号分隔的文件而没有逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆