[英]Program ending before output is finished writing to file
顾名思义,我有一个程序在完成将其输出写入文件之前结束。 我不确定这是C#的限制还是什么。
这是有问题的代码:
static void Main(string[] args)
{
StreamReader source = new StreamReader(filepathsource);
StreamWriter dest = new StreamWriter(filepathdest,false);
dest.WriteLine("Department,Number,Long Title,Description");
string line;
bool dept = false;
bool num = false;
bool title = false;
string temp;
while ((line = source.ReadLine()) != null)
{
dept = false;
num = false;
title = false;
temp = "";
line = line.TrimStart(' ', '\t');
if (line.Length > 0)
{
foreach (char z in line)
{
if (!dept)
{
if (z == ' ') //---a space will mark the end of the department code.
{
dept = true;
temp += ",\""; //make a comma and a double quote to ensure the number that follows is a string
}
else
temp += z;
}
else if (!num)
{
if (z == '.') //---a period will mark the end of the course number
{
num = true;
temp += "\",\""; //close the string, make a comma, and start a new string
}
else
temp += z;
}
else if (!title)
{
if (z == '.') //---a period will mark the end of the course title
{
title = true;
temp += "\",\""; //close the string, make a comma, and start a new string
}
else
temp += z;
}
else if(z == '"') //---We are in the Description now and if we find a double quote
{
temp += "''"; //replace it with two single quotes
}
else
temp += z;
}
temp += "\""; //---end the last string
dest.WriteLine(temp); //---write the comma delimited line to the output file.
}
}
}
该程序旨在从文本文件(与ASCII或Unicode不相关)中提取课程目录信息,按照特定格式对其进行解析,然后将其分离为字段,并以CSV格式注入到另一个文本文件中。 然后将此CSV格式的信息合并到MSSQL数据库中。
但是在我看来,源文件中的信息越长,程序在切出最后几行文本时遇到的问题就越多。 我该怎么做才能纠正这个问题? 我去年在旧信息上运行了该程序,它似乎运行得很好。
使用流后,请务必关闭它们。
最后添加:
dest.Close();
source.Close();
更好的方法是将它们放在using
语句中:
static void Main(string[] args)
{
using(StreamReader source = new StreamReader(filepathsource))
{
using(StreamWriter dest = new StreamWriter(filepathdest,false))
{
dest.WriteLine("Department,Number,Long Title,Description");
string line;
bool dept = false;
bool num = false;
bool title = false;
string temp;
while ((line = source.ReadLine()) != null)
{
......
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.