Writing strings to file

  • Thread starter Thread starter John
  • Start date Start date
J

John

Hi

Is there any easy way to write strings into a file for debugging purposes?

Thanks

Regards
 
John said:
Hi

Is there any easy way to write strings into a file for debugging purposes?

Thanks

Regards

You will need a reference to System.IO

Using sw As New StreamWriter(MyFileName, True) 'last parameter tells sw to
append to file

sw.WrileLine(MyText)
End Using
 
Here is some C# code.

This can write to your computers temp directory and "pop it" in notepad.


But I would also look at a complete logging solution.



private void WriteAndOrPopDebugMessage(string msg)
{
bool popTextFile = false;

bool generateTempFile = false;

//set those values to config file settings
popTextFile =true;//better to read from config file
generateTempFile =true;//better to read from config file

if (popTextFile || generateTempFile )
{
string fileName = WriteToTempFile(string.Empty, msg);
if (popTextFile)
{
System.Diagnostics.Process.Start(fileName);
}
else
{
Console.WriteLine(fileName);
}
}
}

public string WriteToTempFile(string prefix, string toWrite)
{

string fileName = System.IO.Path.GetTempFileName();
fileName = fileName.Replace(".tmp", ".txt");
return WriteAFile(fileName, prefix, toWrite);

}


public string WriteAFile(string fileName , string prefix, string
toWrite)
{

System.IO.StreamWriter writer = null;
System.IO.FileStream fs = null;

try
{

// Writes text to a temporary file and returns path

fs = new System.IO.FileStream(fileName,
System.IO.FileMode.Append, System.IO.FileAccess.Write);
// Opens stream and begins writing
writer = new System.IO.StreamWriter(fs);
writer.BaseStream.Seek(0, System.IO.SeekOrigin.End);
writer.WriteLine(toWrite);
writer.Flush();

return fileName;

}
finally
{
if (null != writer)
{
writer.Close();
}
if (null != fs)
{
fs.Close();
}
}
}
 
Back
Top