i develop one windows service in the i use filesystemWatcher if any event is raised i write that information into text file in e:\ location all work fine but
while the service is running suppose i open that text file it shows the content but after at the stop that service an un handled exception thrown what is the problem
what i understand is when the file is open we try to write the content on that file through stream that error will come what is the solution for this problem
Loading
Dorababu MekaPosted Sep 6, 2010, 11:42 PM
A sample code
public bool saveBatchHeader(string m_strPath)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine();
sb.Append(m_strRecordTypeCode.PadLeft(1, '0'));
sb.Append(m_strServiceClassCode.PadLeft(3, '0'));
sb.Append(m_strCompanyName.PadRight(16, ' '));
sb.Append(m_strCompanyDiscretionaryData.PadRight(20, ' '));
sb.Append(m_strCompanyIdentification.PadRight(10, ' '));
sb.Append(m_strStandardEntryClassCode.PadRight(3, ' '));
sb.Append(m_strCompanyEntryDescription.PadRight(10, ' '));
string m_strCompanyDescripDate = m_strCompanyDescriptiveDate.Replace("/", "");
sb.Append(m_strCompanyDescripDate.PadLeft(6, '0'));
string m_strEffDate = m_strEffectiveEntryDate.Replace("/", "");
sb.Append(m_strEffDate.PadLeft(6, '0'));
sb.Append(m_strJulianDate.PadRight(3, ' '));
sb.Append(m_strOriginatorStatusCode.PadRight(1, ' '));
sb.Append(m_strOriginationDFIIdentification.PadLeft(8, '0'));
sb.Append(m_strBatchNumber.PadLeft(7, '0'));
StreamWriter sw = File.AppendText(m_strPath);
sw.Write(sb);
sw.Close();
}
Suthish NairPosted Sep 6, 2010, 4:13 PM
here an example..
using (FileStream fs = new FileStream(Server.MapPath("1.txt"), FileMode.Append, FileAccess.Write))
{
fs.Close();
TextWriter tw = new StreamWriter(Server.MapPath("1.txt"), true);
tw.WriteLine(System.Environment.NewLine + DateTime.Now);
tw.Close();
}
Sam HobbsPosted Sep 6, 2010, 2:52 PM
ShankeyPosted Sep 6, 2010, 5:22 AM
You cannot write to already open file. But you can change like if it is already open create copy of that file to another place and then edit content and once the file is not in use you can replace with your copy. Following is the code to identify whether the file is in use or not. Hope it will help you. But dont forget to mark my answer as accepted if it helped you :)