StreamWriter.Write doesn't write to file; no exception thrown
Use
System.IO.File.WriteAllText(@"path\te.txt", "text");
Why does my StreamWriter not write to file?
I would rewrite your Log class to avoid the close part.
Just open, write and close after finishing the write part
class MySimpleLog
{
private string _filename;
public MySimpleLog(string filename)
{
_filename = filename;
}
public void AppendText(string msg)
{
// Create an instance of StreamWriter to write text to a file.
// The using statement also closes the StreamWriter.
using (StreamWriter sw = new StreamWriter(_filename, true))
{
// Add some text to the file.
sw.WriteLine(msg);
}
}
}
In this way the using statement will close the stream and you don't have to worry about closing it. Indeed closing the stream could be very troublesome if something unexpected happens in your code. (Like an exception that change your code flow).
This is just a starting point to have the code tested and verified, but you could add some more complex logic following the pattern given. For example you could add a constructor with a flag to add a timestamp for everyline (or a flag to add a separator line, or a flag to recreate the file if exists...)
class MySimpleLog
{
private string _filename;
private bool _addtime;
public MySimpleLog(string filename)
{
_filename = filename;
}
public MySimpleLog(string filename, bool addtime)
{
_filename = filename;
_addtime = addtime;
}
public void AppendText(string msg)
{
// Create an instance of StreamWriter to write text to a file.
// The using statement also closes the StreamWriter.
using (StreamWriter sw = new StreamWriter(_filename, true))
{
// Add some text to the file.
msg = (_addtime ? DateTime.Now.ToString() + ": " + msg : msg);
sw.WriteLine(msg);
}
}
}
FINALLY: Keep in mind that specialized log libraries exists well tested and free to use. Perhaps you could invest some of your time in learning them
Log4Net
NLog
StreamWriter won't write to log file
You need to close the StreamWriter
. It's best to use a using
block for this, as it guarantees that the StreamWriter
will be closed, even if an exception is thrown.
using (var log = GetLog()){
log.WriteLine("["+DateTime.Now + "]: ");
}
...
public StreamWriter GetLog(){
if (!File.Exists(@"" + LogFile))
{
return new StreamWriter(@"" + LogFile);
}
else {
return File.AppendText(@"" + LogFile);
}
}
StreamWriter doesn't write to a file that doesn't exist
You're missing a constructor which takes a boolean that can aid in creating the file:
using (StreamWriter stream = new StreamWriter(filePath, false)) {
stream.Write(data);
stream.Close();
}
The logic is actually is little more complex than that, however:
public StreamWriter(
string path,
bool append
)Determines whether data is to be appended to the file. If the file
exists and append is false, the file is overwritten. If the file
exists and append is true, the data is appended to the file.
Otherwise, a new file is created.
StreamWriter Not working in C#
You need to Flush()
the StreamWriter after write.
By default StreamWriter is buffered that means it won't output until it receives a Flush() or Close() call.
Also you can also try to close it like this:
sw.Close(); //or tw.Flush();
You can also have a look at StreamWriter.AutoFlush Property
Gets or sets a value indicating whether the StreamWriter will flush
its buffer to the underlying stream after every call to
StreamWriter.Write.
The other option which is now a days very popular and recommended is to use the using statement which takes care of it.
Provides a convenient syntax that ensures the correct use of
IDisposable objects.
Example:
using(var sr = new StreamReader("C:\\Temp1\\test1.txt"))
using(var sw = new StreamWriter("C:\\Temp2\\test2.txt"))
{
...
}
Write text to file using stream writer
You should dispose of the StreamWriter after writing to it.
eg:
var MIS = string.Join(" ", MentionsList.ToArray());
string Mentionsintext = MIS.ToString();
using (StreamWriter MentionFile = new StreamWriter(@"C:\Users\User\Documents\Mentions.txt")) {
MentionFile.WriteLine(Mentionsintext + Environment.NewLine);
}
For more examples: see https://www.dotnetperls.com/streamwriter
StreamWriter can't write in few folders(and no exception thrown) but it can write in different folder locations
It is a Folder security issue, account I'm using doesn't have rights to write to that folder. So to write to it
1) Open Folder Property,
2) Navigate to 'Security' tab
3) Click 'Edit' and 'Add' in Newly opened tab
4) enter your pc name/... click 'Ok'
That should solve this issue. Thanks for your comments though :)
I'm trying to write text to a .txt file but it doesn't work
I just had to run visual studio as administrator, dont waste time trying to add more answers\comments, this problem is solved
Streamwriter not throwing exception
FileStream fs = new FileStream(fileName, FileMode.Append);
This will create the file if it doesn't exist (and append to it if it does).
Assuming from your post (there is no question in it!) you don't want it to create a file first call File.Exists
to ensure the file exists.
Related Topics
Does .Net Have a Built-In Eventargs<T>
How to Pass Objects into an Attribute Constructor
How to Generate and Auto Increment Id with Entity Framework
Does Anyone Know of a Good C# API for Subversion
How to Get an Extension Method to Change the Original Object
Using String as a Lock to Do Thread Synchronization
How to Programmatically Create, Read, Write an Excel Without Having Office Installed
Calling SQL Defined Function in C#
Creating a Database Programmatically in SQL Server
How to Connect to a Ms Access File (Mdb) Using C#
Should Idisposable.Dispose() Be Made Safe to Call Multiple Times
Synchronizationlockexception on Monitor.Exit When Using Await
How to Remove Numbers from String Using Regex.Replace
Escape Quote in C# for JavaScript Consumption