如何在C#中使用StreamWriter写入文件?

发布于 2025-01-31 09:10:34 字数 1459 浏览 1 评论 0原文

我无法正确写入文件。该程序读取文件并在控制台上显示毫无问题,但是我有一些问题试图写入此文件。

我有这样的方法:

public static string Temp(string f)
{
    int v = f.IndexOf(":");
    string rez = f.Substring(0, v + 1);
    string st = f.Substring(v + 1);
    int[] tm = Numbers(st, ' ', '\t');

    if (tm == null)
        return rez + "mistake";
    else
        return String.Format("{0} {1} {2} {3}", rez, tm.Average(), tm.Min(), tm.Max());
}

文件内容如下:

mistake
mistake

我的一些代码:

static void Main(string[] args)
{
    Show();
    Console.ReadKey();
}

public static void Show()
{
    string file = "data3.txt";
    char[] s = { ' ', '\t', '\r' };
    int[][] jaggedArray;

    ReadFile(file, s, out jaggedArray);

    StreamWriter sw = new StreamWriter("result3.txt");
    Result(file, jaggedArray, sw);
}

public static void ReadFile(string f, char[] s, out int[][] jaggedArray)
{
    using (StreamReader n = new StreamReader(f))
    {
        string[] l = n.ReadToEnd().Split('\n');
        jaggedArray = new int[l.Length][];

        for (int i = 0; i < l.Length; i++)
        {
            string t = l[i].Replace("\r", String.Empty);
            Console.WriteLine(Temp(t));
        }
    }
}

static void Result(string f, int[][] x, TextWriter n)
{
    foreach (int[] tm in x)
    {
        n.WriteLine(Temp(f));
    }

    n.Close();
}

问题是temp(String f)有效地工作并显示在控制台中但不在文件中的数据。我会很感谢您的帮助

I can't write into a file correctly. The program reads the file and displays it on console with no problem, but I have some issues trying to write into this file.

I have this method:

public static string Temp(string f)
{
    int v = f.IndexOf(":");
    string rez = f.Substring(0, v + 1);
    string st = f.Substring(v + 1);
    int[] tm = Numbers(st, ' ', '\t');

    if (tm == null)
        return rez + "mistake";
    else
        return String.Format("{0} {1} {2} {3}", rez, tm.Average(), tm.Min(), tm.Max());
}

File contents is returned like this:

mistake
mistake

Some of my code:

static void Main(string[] args)
{
    Show();
    Console.ReadKey();
}

public static void Show()
{
    string file = "data3.txt";
    char[] s = { ' ', '\t', '\r' };
    int[][] jaggedArray;

    ReadFile(file, s, out jaggedArray);

    StreamWriter sw = new StreamWriter("result3.txt");
    Result(file, jaggedArray, sw);
}

public static void ReadFile(string f, char[] s, out int[][] jaggedArray)
{
    using (StreamReader n = new StreamReader(f))
    {
        string[] l = n.ReadToEnd().Split('\n');
        jaggedArray = new int[l.Length][];

        for (int i = 0; i < l.Length; i++)
        {
            string t = l[i].Replace("\r", String.Empty);
            Console.WriteLine(Temp(t));
        }
    }
}

static void Result(string f, int[][] x, TextWriter n)
{
    foreach (int[] tm in x)
    {
        n.WriteLine(Temp(f));
    }

    n.Close();
}

The thing is that Temp(string f) works and shows data in console but not in file. I would appreciate some help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

本王不退位尔等都是臣 2025-02-07 09:10:34

您在业务逻辑上有很多问题:

//TODO: Bad Practice: names are distracting: Result writes into file, it doesn't solve for result 
//TODO: Bad practice: names are unreadable: no-one can guess that n is writer (and not, say, a count)
static void Result(string f, int[][] x, TextWriter n)
{
    //TODO: unreadable name - what is "tm in x"?
    foreach (int[] tm in x)
    {
        //TODO: possibly an error: you ignore x and tm at all
        // instead you write a (processes) filename (f) into the file (n) // what names! tm, x, n... 
        n.WriteLine(Temp(f));
    }
    //TODO: bad practice - closing / disposing instance which is not created by the routine
    n.Close();
}

我无能为力 ,
我尝试帮助文件操作。

为什么不摆脱streamstreamReader \ streamWriter并使用file> file类来读写并写入文件?

using System.Linq;
...

// why do we need out here? Let's just return the result
static int[][] ReadFile(string fileName) {
  // Here we read all file's lines into string array - l
  string[] lines = File.ReadAllLines(fileName);
     
  // From now on we can forget about file and manipulate with 
  // lines - lines read from the file 
  result = new int[lines.Length][];

  // Note, that you put nothing into result, just print out lines
  foreach (string line in lines)
    Console.WriteLine(Temp(line));

  return result;
}

static void WriteFile(string fileName, int[][] data) {
  // Here we prepare lines to be written into the file
  // for each array and its index within jagged array x we should
  // create a line to be written.
  // Here we ignore both array and index and put the file name instead - Temp(f)
  // TODO: provide correct business logic here:
  //    (array, index) => what should be written into file's line
  var lines = data
    .Select((array, index) => Temp(fileName)); 

  // Then we just write the lines prepared into the file
  File.WriteAllLines(fileName, lines);
}

You have many issues with business logics:

//TODO: Bad Practice: names are distracting: Result writes into file, it doesn't solve for result 
//TODO: Bad practice: names are unreadable: no-one can guess that n is writer (and not, say, a count)
static void Result(string f, int[][] x, TextWriter n)
{
    //TODO: unreadable name - what is "tm in x"?
    foreach (int[] tm in x)
    {
        //TODO: possibly an error: you ignore x and tm at all
        // instead you write a (processes) filename (f) into the file (n) // what names! tm, x, n... 
        n.WriteLine(Temp(f));
    }
    //TODO: bad practice - closing / disposing instance which is not created by the routine
    n.Close();
}

I can't help you with the business logic (I don't know what the routine is supposed to do), but
I try to help with file manipulations.

Why don't get rid of Streams, StreamReader \ StreamWriter and use File class to read and write the file?

using System.Linq;
...

// why do we need out here? Let's just return the result
static int[][] ReadFile(string fileName) {
  // Here we read all file's lines into string array - l
  string[] lines = File.ReadAllLines(fileName);
     
  // From now on we can forget about file and manipulate with 
  // lines - lines read from the file 
  result = new int[lines.Length][];

  // Note, that you put nothing into result, just print out lines
  foreach (string line in lines)
    Console.WriteLine(Temp(line));

  return result;
}

static void WriteFile(string fileName, int[][] data) {
  // Here we prepare lines to be written into the file
  // for each array and its index within jagged array x we should
  // create a line to be written.
  // Here we ignore both array and index and put the file name instead - Temp(f)
  // TODO: provide correct business logic here:
  //    (array, index) => what should be written into file's line
  var lines = data
    .Select((array, index) => Temp(fileName)); 

  // Then we just write the lines prepared into the file
  File.WriteAllLines(fileName, lines);
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文