如何使用visual c#和streamwriter在循环中更改文本文件的名称

时间:2015-06-25 18:12:21

标签: c# streamwriter

我正在尝试编写一个循环读取列表,并根据数据的小时将该列表的一部分保存到不同的文本文件中。我想根据数据的小时来命名文本文件。

以下是相关代码:

private StreamWriter filename;
string[] hour = {"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23}

private void btn_hourfiles_click(object sender, EventArgs e)
{
    int sizeoflist = Data_List.Count(); //This is the list containing the data
    for (int i = 0; i<sizeoflist,i++)
    {
       string[] listsplit = Data_List[i].Split(":");
       for (int j = 0; j<24; j++)
       {
           if (listsplit[2] == hour[j])
           {
            string[] datesplit = txt_DATE.Text.Split('-');//splits input date
            filename = datesplit[0] + '_' + dateplit[1] + '_' + datesplit[2] + '_' + hour[j] + '.dat'
            filename = new StreamWriter(new FileStream(Data_List[i], FileMode.Append, FileAccess.Write));
            }
       }
    }
 }

问题:我无法更改StreamWriter filename。我收到一条错误消息:Cannot implicitly convert type string to System.IO.StreamWriter

问题:如何更改变量文件名?

2 个答案:

答案 0 :(得分:0)

The code you post is not getting compiled. Try next time to post the input so it will be simpler to help and answer to your question. Anyway, I tried to help you according to what you wrote above, hope it will help you class Program { static void Main(string[] args) { MyTest test = new MyTest(); test.Foo(); } } class MyTest { private StreamWriter streamWriter; string[] hour = { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" }; public void Foo() { string txt_DATE = "25-02-2015"; string[] Data_List = { "12:05:10", "02:15:00", "14:15:22" }; int sizeoflist = 3; // Data_List.Count(); //This is the list containing the data for (int i = 0; i < sizeoflist; i++) { string[] listsplit = Data_List[i].Split(':'); for (int j = 0; j < 24; j++) { if (listsplit[2] == hour[j]) { string[] datesplit = txt_DATE.Split('-');//splits input date var filename = datesplit[0] + '_' + datesplit[1] + '_' + datesplit[2] + '_' + hour[j] + ".dat"; streamWriter = new StreamWriter(new FileStream("C:\\" + filename, FileMode.Append, FileAccess.Write)); } } } } }

答案 1 :(得分:0)

问题在于StreamWriter如此声明:

private StreamWriter filename;

但随后分配了一个字符串:

filename = datesplit[0] + '_' + dateplit[1] + '_' + datesplit[2] + '_' + hour[j] + '.dat'

建议:对文件名和StreamWriter使用单独的变量。