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

How to Change the name of a Text File in a loop using visual c# and 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

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

您 post 的代码没有被编译。下次尝试 post 输入,这样可以更轻松地帮助和回答您的问题。 不管怎样,我已经按照你上面写的尽量帮到你了,希望对你有帮助

class 程序 {

    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));
                }
            }
        }
    }
}

问题是 StreamWriter 是这样声明的:

private StreamWriter filename;

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

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

建议:为文件名和 StreamWriter.

使用单独的变量