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"文件,并将外部 using 块中的代码写入文件...

我很不擅长解释这些问题,但基本上我试图在第二个 using 块中获取信息,以便"4222013Average.txt"在输出文件中命名......

4

2 回答 2

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() + ",");
    }
}
于 2013-04-23T01:44:26.723 回答
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);
于 2013-04-23T01:29:16.163 回答