输出文本文件

时间:2013-04-23 01:14:03

标签: c# asp.net-mvc-4 text-files

我正在将信息写入文件,并将其命名为"//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" ...

2 个答案:

答案 0 :(得分: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() + ",");
    }
}

答案 1 :(得分: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);