【问题标题】:C# - Preventing from writing append lines in file if file is existC# - 如果文件存在,则防止在文件中写入附加行
【发布时间】:2017-11-03 17:46:20
【问题描述】:

救命!!如何制作一个程序来阻止程序在现有文件中追加新行?

代码:

   if (File.Exists(path)) 
        {

        }
        FileStream fs = null;
        if (!File.Exists(path))
        {
            using (fs = File.Create(path))
            {
                MessageBox.Show("Text File Created Succesfully!");
            }
        }
        string[] OrigProductItems = { "Blood Pressure Monitor\t", "Digital Scale\t\t", "Footrest\t\t", "Health Care Thermometers", "Massager\t\t" };
        int[] OrigProductQty = {30, 10, 5, 20, 10};
        double[] OrigProductPrice = { 799.75, 499.75, 99.95, 79.75, 1990.75 };


        if (File.Exists(path))
        {
            using (StreamWriter sw = File.AppendText(path))
            {
                for (ctrl = 0; ctrl < 5 ; ctrl++)
                {
                    sw.WriteLine(OrigProductItems[ctrl] + "\t" + OrigProductQty[ctrl] + "\t\t" + OrigProductPrice[ctrl]);
                }
            }
        }
    }

【问题讨论】:

  • 也许检查并返回? if (File.Exists(path)) return;
  • 这是您可以控制其功能的代码吗?或者是您无法控制的其他代码,因此您无法更改行为?

标签: c# file stream filestream


【解决方案1】:

只是否定你已经拥有的东西

    if (!File.Exists(path)) // append only if file doesnt exist
    {
        using (StreamWriter sw = File.AppendText(path))
        {
            for (ctrl = 0; ctrl < 5 ; ctrl++)
            {
                sw.WriteLine(OrigProductItems[ctrl] + "\t" + OrigProductQty[ctrl] + "\t\t" + OrigProductPrice[ctrl]);
            }
        }
    }

【讨论】:

  • 非常感谢!!
猜你喜欢
  • 2013-12-24
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 2020-06-18
  • 2020-08-22
  • 2021-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多