Filestream.write does not work - c#

I used the following code to write on *.txt file, but nothing happens. Even, there is no exception.
FileStream fs = new FileStream(#"D:\file.txt",FileMode.OpenOrCreate,FileAccess.Write,FileShare.None); //Creating a stream with certain features to a file
StreamWriter writer = new StreamWriter(fs); //Use the fs to write
// writer.WriteLine(Text.Text); none of the following methods works
writer.Write("aaaaaaaaaaaa");
fs.Close();
Thanks

Try to enclose it in a using block like this:
using ( FileStream fs = new FileStream(#"D:\file.txt",FileMode.OpenOrCreate,FileAccess.Write,FileShare.None))
using (StreamWriter fw = new StreamWriter(fs))
{
fw.Write("aaaaaaaaaaaa");
}
A StreamWriter buffers data before writing it to the underlying stream. You need to flushes the buffer by disposing the StreamWriter

Related

How can I convert StreamWriter to a Stream?

I am trying to create a file using FileHelpers and then write that file out using SshNet all in memory.
So far I have the following:
var engine = new FileHelperEngine<MyObject>();
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);
engine.WriteStream(sw, MyData);
SshHelper ssh = new SshHelper("","","");
ssh.WriteFile("MyPath", sw.BaseStream);
However my issue is with the WriteFile method since it requires a Stream parameter and when I run my code I am getting an empty file.
How can I convert my StreamWriter (sw variable) into a Stream parameter?
EDIT:
I've tried both(not at the same time):
ms.Seek(0, SeekOrigin.Begin);
ms.Position = 0;
and it still writes a 0 byte file.
I further tested by using FileHelper to write to my local disk to verify that I have data. (Which I do)
your MemoryStream is the stream, the StreamWriter is just writing to it. Try passing ms in, instead of sw.
Before WriteFile try setting the Position of your Stream to 0: ms.Seek( 0, SeekOrigin.Begin )

Modify File Stream in memory

I am reading a file using StreamReader fileReader = File.OpenText(filePath). I would like to modify one line in the file in memory and push the modified stream to another method.
What I would like to avoid is reading the whole file into a string and modifying the string (doesn't scale). I would also like to avoid modifying the actual file.
Is there a straightforward way of doing this?
There is no built-in way to do that in .Net framework.
Stream and StreamReader/StreamWriter classes are designed to be chained if necessary (like GZipStream wraps stream to compress it). So you can create wrapper StreamReader and update data as you need for every operation after calling wrapped reader.
You can open two stream -one for read, one for write- at the same time. I tested simple code that works, but not sure that's what you want:
// "2.bar\r\n" will be replaced by "!!!!!\r\n"
File.WriteAllText("test.txt",
#"1.foo
2.bar
3.fake");
// open inputStream for StreamReader, and open outputStream for StreamWriter
using (var inputStream = File.Open("test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = new StreamReader(inputStream))
using (var outputStream = File.Open("test.txt", FileMode.Open, FileAccess.Write, FileShare.Read))
using (var writer = new StreamWriter(outputStream))
{
var position = 0L; // track the reading position
var newLineLength = Environment.NewLine.Length;
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
// your particular conditions here.
if (line.StartsWith("2."))
{
// seek line start position
outputStream.Seek(position, SeekOrigin.Begin);
// replace by something,
// but the length should be equal to original in this case.
writer.WriteLine(new String('!', line.Length));
}
position += line.Length + newLineLength;
}
}
/* as a result, test.txt will be:
1.foo
!!!!!
3.fake
*/
As you can see, both streams can be accessed by StreamReader and StreamWriter at the same time. And you can also manipulate both read/write position as well.

Stream not writing on a file

Is there anything wrong with this piece of code ? It's opening the file , yet it doesn't write on it.
fl = new FileStream(path, FileMode.OpenOrCreate);
sw = new StreamWriter(fl);
sw.WriteLine("Hello ");
The proper way of doing this would be:
using (StreamWriter sw = new StreamWriter(new FileStream(path, FileMode.OpenOrCreate)))
sw.WriteLine("Hello ");
This will call sw.Flush(), sw.Close() and sw.Dispose().
StreamReader uses a buffer. You can force the output by using Flush(), but in most cases you should just make sure you use using() which will call Dispose at the end and flush all remaining data.
Have you tried to call Flush method?
sw.Flush();

Is there a way to create a text file using a string name in C#

I'm not sure if it's possible. I usually create txt files like this:
FileStream fs = new FileStream("c:\\textFile.txt", FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
but instead of using "c:\textFile.txt" I want to create a file using a string name. Is there a way to do it?
Of course. The first argument to the FileStream constructor takes a string. You've just passed it a string literal (defined in your source code file). It sounds like you want to pass a string variable instead:
string path = // get string from somewhere. A file save dialog, maybe?
FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
May I suggest that you spend some time with a C# tutorial? Microsoft has some good tutorials and samples. With all due respect, and we were all there once, you've got some holes in your knowledge that will trip you up.
I'm not sure I'm following what you're asking for. You just asked if u could do that:
string filename = "c:\\textFile.txt";
FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
or as you specified
FileStream fs = new FileStream(YourTextBox.Text, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);

Cannot write to a textfile using timer in C#

I am still newbie to C# and I'm making a test program that writes the DateTime.Now every second. I tried using this and it worked:
StreamWriter sw = new StreamWriter("D:\Hello.txt", true);
sw.WriteLine(DateTime.Now);
sw.Close();
However, when I tried including a FileStream, it didn't work. What seems to be the problem? Here's my code:
FileStream fs = new FileStream(#"D:\Hello.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(DateTime.Now);
sw.Close();
fs.Close();
Note: I am using a timer, it executes the code every second..
Update:
I tried placing the code(the one that has the filestream) inside a button (w/out timer). Whenever I clicked the button, it just replaces the line in the textfile.. This is a code that appends a text to the textfile:
StreamWriter sw = new StreamWriter("D:\Hello.txt", true);
How will I do it in a filestream? I cannot use FileMode.Append in FileStream because it required=s the FileAccess to be write-only.
Since you are executing the code every second then its not a good idea to create FileStream and StreamWriter object everytime, because sometimes the file will remain under lock condition and the filestream will miss to acquire the handle.
As you are writing to single file its good to initialize a FileStream and subsequent StreamWriter in the constructor while leaving the refrence to them in class scope;then calling it every second on a thread for sw.WriteLine(DateTime.Now); should help.
And further never miss try catch in a filestream. They help a lot to locate the discrepancies.
May be try to use File?
File.AppendAllText(#"D:\Hello.txt", DateTime.Now.ToString());
or
File.WriteAllText(#"D:\Hello.txt", DateTime.Now.ToString());
to overwrite
You should use something like this because it works fine for me. If it does not work for you, you have to add more details
using (var fs = new FileStream("path", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
fs.Seek(0, SeekOrigin.End);
using (StreamWriter sw = new StreamWriter(fs) { AutoFlush = true })
{
sw.WriteLine("my text");
}
}
But remember I would not create it every second. Why don t you store a Streamwriter object as field when you call Timer.Start?
So you would not have to create it every second. (rememer to dispose it when you stop the timer)
Should work:
FileStream fs = new FileStream(#"D:\Hello.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(DateTime.Now);
sw.Flush();
sw.Close();
fs.Close();
I already solved it.. :) I just have to use FileMode.Append, FileAccess.Write as an argument in the filestream. Reason for not doing FileMode.Append earlier is because it needs FileAccess to be Write only. I thought switching the FileAcess to Write only will prevent the user from reading the file. So stupid of me.. This is my code:
private void timer1_Tick(object sender, EventArgs e)
{
FileStream fs = new FileStream(#"D:\Hello.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(DateTime.Now);
lbTimer.Items.Add(DateTime.Now);
sw.Close();
fs.Close();
}
Last question, what is setting the FileAccess to Write only for when you can still read it?
Try calling StreamWriter.Flush() before StreamWriter.Close().
You might wanna look here
How to: Write to a Text File (C# Programming Guide)
http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx

Categories

Resources