2017-06-02 68 views
0

帮助!!我怎样才能让程序停止在已有文件中追加新行?C# - 如果文件存在,防止在文件中写入追加行

代码:

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]); 
       } 
      } 
     } 
    } 
+1

或许检查并返回? 'if(File.Exists(path))return;' –

+0

这是你的代码,你可以控制它做什么?还是它是你不能控制的其他代码,所以你不能改变行为? –

回答

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]); 
      } 
     } 
    } 
+0

非常感谢你! –