2013-04-23 123 views
0

我正在將信息寫入文件,並將其命名爲"//Average+DateTime.txt";我想我的代碼會更容易比我想澄清:輸出文本文件

String path=bama(); 

if(path.Contains(".txt")) { 
    StreamWriter sw= 
     new StreamWriter(
      "C:/Users/msilliman11/Average" 
      +DateTime.Now.ToString("yyyyMMdd") 
      +".txt" 
      ); 
} 

String ElementsNum=RoundedValues.Count.ToString(); 
DateTime dt=System.DateTime.Now; 

using(var NewFile=File.Create(path)) { 
    using(var writeIt=new StreamWriter(NewFile)) { 
     writeIt.Write(
      "NA"+"," 
      +dt.Hour.ToString()+","+dt.Minute+"," 
      +dt.Day+","+dt.Month.ToString()+","+dt.Year.ToString()+"," 
      +"ALTEST "+","+"ALTEST "+","+heatgrade 
      +" "+","+"  "+","+heatname+"," 
      +DT2.Columns[3].ToString()+","+heatgrade+"," 
      +"OE2"+","+","+","+","+","+","+","+" "+ElementsNum+"," 
      ); 

     foreach(
      var pair in 
      RoundedValues.Zip(
       Elements, (a, b) => new { 
        A=a, 
        B=b 
       })) { 
      writeIt.Write(pair.B.ToString()+","+pair.A.ToString()+","); 
     } 
    } 
} 

我的問題是,我需要命名"Average"文件,並在寫入文件外使用的代碼塊...

我敢壞在解釋這些問題,但基本上即時通訊試圖讓第二塊使用的信息,被命名爲輸出文件中"4222013Average.txt" ...

+0

您在第一「命名它作爲//Average+DateTime.txt說:」然後你提到的「命名‘4月22日/ 2013Average.txt’,所以它的格式是你想要的嗎? – 2013-04-23 01:18:10

+0

對不起,最後一個是正確的,我把斜線放在那裏也犯了一個錯誤, – 2013-04-24 20:51:44

回答

1

如果我正確地理解你的問題,我認爲這可能更好地爲你。

var toFile = Path.Combine(@"C:\Users\msilliman11\", 
    string.Format("Average{0}.txt", DateTime.Now.ToString("yyyyMMdd"))); 
var dt = DateTime.Now; 
using (var fs = File.OpenWrite(toFile)) 
using (TextWriter sw = new StreamWriter(fs)) 
{ 
    sw.Write(string.Join(",", 
     "NA", 
     dt.Hour, 
     dt.Minute, 
     dt.Day, 
     dt.Month, 
     dt.Year, 
     "ALTEST ", 
     "ALTEST ", 
     heatgrade, 
     " ", 
     "  ", 
     heatname, 
     DT2.Columns[3], 
     heatgrade, 
     "OE2", 
     string.Empty, 
     string.Empty, 
     string.Empty, 
     string.Empty, 
     string.Empty, 
     string.Empty, 
     string.Empty, 
     " ", 
     ",")); 

    foreach (var pair in RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b })) 
    { 
     writeIt.Write(pair.B.ToString() + "," + pair.A.ToString() + ","); 
    } 
} 
+0

完美!謝謝! – 2013-04-24 23:02:42

0

這並不完全清楚是什麼問題是,除了:

你說你想命名文件:4/22/2013Average.txt。這不可能。文件名中不允許使用正斜槓。

這是你需要知道的嗎?如果沒有,請更清楚。

另外一個提示:請使用string.Format()你的代碼更易讀:

string text = string.Format("NA,{0},{1},{2},{3},{4},ALTEST,ALTEST ,{5} ,  ,{6},{7},{5},OE2,,,,,,, {8},", 
     dt.Hour, 
     dt.Minute, 
     dt.Day, 
     dt.Month, 
     dt.Year, 
     heatgrade, 
     heatname, 
     DT2.Columns[3], 
     ElementsNum); 
    writeIt.Write(text);