我正在尝试创建一个日志文件并写入该文件,我在不同的方法中使用相同的文件,我收到一个错误。如果我做错了,请纠正我。
foreach (var corporationObj in corporations)
{
// Log which corporation it is currenlty doing
_keepItDry.Log("Started Data Summarisation for corporation: @" + corporationObj.Description, w);
// Pass the coporationId and call method to DoProductStatsForCorporation and also pass the log file to continue our logging.
w.Flush();
// w.Close();
w.Dispose();
DoProductStatsForCorporation(corporationObj.Id, path);
}
以下是循环中调用方法的列表:
private void DoProductStatsForCorporation(int corporationId, string logFilePath)
{
var corporationManufacturerRepository = new CorporationManufacturerRepository();
var manufacturerRepository = new ManufacturerRepository();
// Get brand sfor the coporationId passes
var corporationManufacturers = corporationManufacturerRepository.GetAllManufacturersForCorporation(corporationId);
//check before process is used by another object
var fileInfo = new FileInfo(logFilePath);
IsFileLocked(fileInfo);
using (StreamWriter w = File.AppendText(logFilePath))
{
// If brands are existing for the corporation proceed.
if (corporationManufacturers.Any())
{
// loop through each brand to processs
foreach (var corporationManufacturer in corporationManufacturers)
{
#region ProductStats
// get the manufacturer row so that we can know more details about the manufacturer
var manufacturer = manufacturerRepository.GetManufacturer(corporationManufacturer.ManufacturerId);
// Get the countries for the manufacturer
_keepItDry.Log("Started Doing data summarisation for Brand: @ " + manufacturer.Description, w);
// this is common method so extracted to reuse it.
// we need to clos ethe file as we are sending to another function.
w.Flush();
w.Dispose();
DoProductStatsForBrand(manufacturer, logFilePath);
#endregion ProductStats
_keepItDry.AddTolistBox(DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + ": Ended Summarizing data for " + manufacturer.Description, _listBoxLog);
}
}
else
{
_keepItDry.Log(" No Brands are there for the selected Corporation Please check if Brands are mapped for this Corporation ? : @ ", w);
_keepItDry.AddTolistBox(DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + " : No Brands are there for the selected Corporation Please check if Brands are mapped for this Corporation ", _listBoxLog);
}
// w.Flush();
// w.Dispose();
}
// GC.Collect();
}
来到下一家公司后,我得到“当前档案已关闭”。
答案 0 :(得分:1)
首先你有
using (StreamWriter w ...
然后在你内心
`foreach` loop
你拥有的内容
w.Flush();
w.Dispose();
你刚刚处理了你的对象 - 它是如何运作的?
如果您有2个corporationManufacturers
,则会进行一个循环,然后出现错误...
using
是您的处置机制。你只需要一个标志来验证块是否完好。
答案 1 :(得分:0)
您可以使用StreamWriter
来编写文件。
写完文件后处理文件。
streamWriter.Flush();
streamWriter.Close();
Close()
也会调用Dispose()
方法。