C#streamreader和streamwriter到同一文件

时间:2018-09-22 13:09:58

标签: c# stream streamreader streamwriter

我如何读写同一文件?

我的代码示例如下:

List<string> Data = new List<string>();

StreamReader sr = new StreamReader(@"C:\Users\manda\Desktop\Schule\Pos1\HüW2Casino\Spieler1.conf");

StreamWriter sw = new StreamWriter(@"C:\Users\manda\Desktop\Schule\Pos1\HüW2Casino\Spieler1.conf");

while ((line = sr.ReadLine()) != null)
{
    Data.Add(line);
}

int budget = int.Parse(Data[1].Substring(15, 3));

for (int i = 0; i < Data.Count; i++)
{
    if (Data[i] != "ENDE")
    {
        numb = rnd.Next(0, 7);

        if (Data[i].Substring(0,1) == "0" || Data[i].Substring(0, 1) == "1" || Data[i].Substring(0, 1) == "2" || Data[i].Substring(0, 1) == "3" || Data[i].Substring(0, 1) == "4" || Data[i].Substring(0, 1) == "5" || Data[i].Substring(0, 1) == "6" || Data[i].Substring(0, 1) == "7")
        {
            betnumb = int.Parse(Data[i].Substring(0, 1));
            betamount = int.Parse(Data[i].Split(' ') [1]);

            if (betnumb == numb)
            {
                budget += betamount * 7;
            }
            else
            {
                budget -= betamount;
            }

            if (budget < 0)
            {
                sw.Write("Pleite");
                Console.WriteLine("Pleite");
            }
        }
    }
}

但是似乎我无法在同一个文件上读写,因为从未对文件进行任何更改。

也许有人知道我的问题是什么?

2 个答案:

答案 0 :(得分:0)

使用Flush反映文件更改或设置StreamWriter.AutoFlush = true

List<string> Data = new List<string>();
string path = @"C:\Users\manda\Desktop\Schule\Pos1\HüW2Casino\Spieler1.conf"

FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
StreamReader sr = new StreamReader(fs);
StreamWriter sw = new StreamWriter(fs);

while ((line=sr.ReadLine()) != null)
{
   Data.Add(line);
}

int budget = int.Parse(Data[1].Substring(15, 3));

for (int i = 0; i < Data.Count; i++)
{
    if (Data[i] != "ENDE")
    {
       numb = rnd.Next(0, 7);

       if (Data[i].Substring(0,1) == "0" || Data[i].Substring(0, 1) == "1" || Data[i].Substring(0, 1) == "2" || Data[i].Substring(0, 1) == "3" || Data[i].Substring(0, 1) == "4" || Data[i].Substring(0, 1) == "5" || Data[i].Substring(0, 1) == "6" || Data[i].Substring(0, 1) == "7")
       {
           betnumb = int.Parse(Data[i].Substring(0, 1));
           betamount = int.Parse(Data[i].Split(' ') [1]);

           if (betnumb == numb)
           {
              budget+=betamount*7;
           }
           else
           {
               budget -= betamount;
           }

           if (budget < 0)
           {
               sw.Write("Pleite");
               sw.Flush();

               Console.WriteLine("Pleite");
           }
        }
    }
}

答案 1 :(得分:0)

您永远不会关闭StreamWriter。因此,永远不会刷新新内容,并且文件保持打开状态。将StreamWriter括在using语句中,该语句会在末尾或每次离开using块时自动刷新并关闭文件(也可能是由于break,{{1 }}或and例外。

如果打算将数据附加到文件,则可以使用return创建编写器。

由于在写入文件之前已读取文件,因此在写入过程中保持读取器打开是没有意义的。您甚至不需要创建File.AppendText(Path)。只需使用StreamWriter将整个文件读入数组即可。

File.ReadAllLines(Path)

您可以进行一些优化和更正。我猜想您想在到达const string Path = @"C:\Users\manda\Desktop\Schule\Pos1\HüW2Casino\Spieler1.conf"; string[] data = File.ReadAllLines(Path); int budget = Int32.Parse(data[1].Substring(15, 3)); using (StreamWriter sw = File.AppendText(Path)) { for (int i = 0; i < data.Length && data[i] != "ENDE"; i++) { numb = rnd.Next(0, 7); char digit = data[i][0]; // Take the 1st char instead of Substring(0,1). if ('0' <= digit && digit <= '7') { // Chars can be compared like numbers. betnumb = digit - '0'; // You can do math on chars. betamount = Int32.Parse(data[i].Split(' ')[1]); if (betnumb == numb) { budget += betamount * 7; } else { budget -= betamount; } if (budget < 0) { sw.Write("Pleite"); Console.WriteLine("Pleite"); // German for "bankrupt". break; // Probably you don't want to continue looping when bankrupt. } } } } // Automatically flushes and closes the file here. (德语为“ end”)时停止for循环。您可以通过将此条件添加到for循环条件中来做到这一点:"ENDE"

可能您也不想在破产(i < data.Length && data[i] != "ENDE")时继续循环播放。您可以使用budget < 0退出循环。如果执行此操作,则也意味着只写入一次文件。在这种情况下,您甚至可以简化文件编写。而不使用break;

StreamWriter

...您可以简单地写:

using (StreamWriter sw = File.AppendText(Path)) {
    ...
    sw.Write("Pleite");
    ...
}

通过这种简化,代码变为:

    File.AppendAllText(Path, "Pleite");

const string Path = @"C:\Users\manda\Desktop\Schule\Pos1\HüW2Casino\Spieler1.conf"; string[] data = File.ReadAllLines(Path); int budget = Int32.Parse(data[1].Substring(15, 3)); for (int i = 0; i < data.Length && data[i] != "ENDE"; i++) { numb = rnd.Next(0, 7); char digit = data[i][0]; // Take the 1st char instead of Substring(0,1). if ('0' <= digit && digit <= '7') { // Chars can be compared like numbers. betnumb = digit - '0'; // You can do math on chars. betamount = Int32.Parse(data[i].Split(' ')[1]); if (betnumb == numb) { budget += betamount * 7; } else { budget -= betamount; } if (budget < 0) { File.AppendAllText(Path, "Pleite"); Console.WriteLine("Pleite"); break; } } } 中的这些静态方法非常方便,因为它们可以在一条语句中读取或写入以及打开和关闭文件。

您可以简化第一位数字的范围测试。无需重复调用File,只需将第一个字符存储在data[i].Substring(0,1)中。字符的行为类似于整数。您可以比较它们(char digit = data[i][0];)并对其进行计算。 '0' <= digit && digit <= '7'的数字值为digit - '0'

我将文件路径存储在一个常量中,以避免重复。

局部变量和方法参数通常用camelCase编写。因此,我将int重命名为Data