【发布时间】:2015-08-12 13:36:49
【问题描述】:
在对源文件中的某些数据进行某些更改后,我试图从一个文件写入临时文件。在我将这个逻辑提取到它自己的函数中之前,这一直有效。
运行一些测试后,我注意到只有第一行被保存到我指定位置的文件中。调试后,我能够从第二次调用此函数中看到文件位置位于完全不同的位置。
我有两个问题,首先 - 为什么会发生这种情况?第二 - 确保问题得到解决并且不再发生的最佳方法是什么?
str[] 是被分隔符分隔的文件,一次一行。 filename 是包含在文件目录中的特定文件的名称(此程序循环遍历多个文件)。
public static void writeFile(string[] str, string filename)
{
rowCount++;
using (StreamWriter sw = new StreamWriter(filename.Substring(0, filename.Length - 4) + "_tmp.txt", true, System.Text.Encoding.Unicode))
{
string tempString = String.Empty;
for (int i = 0; i < str.Length; i++)
{
if (isMRT)
{
tempString += str[i] + ",";
}
else
{
tempString += str[i] + "|";
}
}
logger.LogMessage("Writting line to file: " + "Row #: " + rowCount + " ,File Path: " + filename.Substring(0, filename.Length - 4) + "_tmp.txt");
sw.WriteLine(tempString);
}
}
编辑: 这是我的目录和文件列表以及调用 write 方法的函数
static string directory = ConfigurationManager.AppSettings["Directory"];
static List<String> fileNames = Directory.GetFiles(directory).ToList();
private static void activityCheck(string filename, string[] allLines)
{
foreach (string nextLine in allLines.Skip(1))
{
string[] tempLine;
if (isMRT)
{
tempLine = nextLine.Split(',');
}
else
{
tempLine = nextLine.Split('|');
}
logger.LogMessage("Checking Activity flag...");
if (tempLine[count].Length == 6)
{
checkColumn(tempLine);
logger.LogMessage("Activity flag is OK");
writeFile(tempLine, filename);
}
else if (tempLine[count].Length > 6)
{
tempLine[count] = tempLine[count].Trim();
checkColumn(tempLine);
logger.LogMessage("FIXED Activity flag");
writeFile(tempLine, filename);
}
else
{
logger.LogMessage("The Activity flag did not have enough numbers in Row #: " +rowCount);
//throw new Exception("There are not enough numbers in the Activity flag");
}
}
}
编辑2: 新制作的临时文件在项目的 bin 文件夹中的 Visual Studio 文件夹中创建。不确定这对以前可能遇到过这种情况的人是否有用。
【问题讨论】:
-
你能告诉我们对 writeFile 的调用吗?
-
filename是什么,文件的实际名称是什么? -
添加了调用发生的函数@Paddy
-
filename 是 filenames[] 中的特定文件.. 所以 filename = filenames[i]
-
与其在这里提问,不如做一些腿部工作。附加调试器,放置断点并查看文件名如何随时间变化,或者如果文件名是相对的,则当前目录如何随时间变化。还有为什么要发明日志记录?抓住一个好的日志框架并使用它(log4net、serilog 等等)
标签: c# file text file-io streamwriter