如何使用visual c#和streamwriter在循环中更改文本文件的名称
本文关键字:文本 文件 循环 visual 何使用 streamwriter | 更新日期: 2023-09-27 17:59:40
我正试图编写一个循环,读取一个列表,并根据数据采集的时间将该列表的部分保存到不同的文本文件中。我想根据获取数据的小时来命名文本文件。
以下是相关代码:
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
问题:如何更改变量文件名?
您发布的代码没有得到编译。下次尝试发布输入,这样帮助和回答您的问题会更简单。不管怎样,我试着根据你上面写的来帮助你,希望它能帮助你
班级计划{
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
使用单独的变量。