Overwriting file in c# using stream writer - c#

I am trying to write a html file using stream writer in c#, it is overwriting the file if close the application and run again, but its appending when I tried to write file for different scenario without closing the application. I wants to overwrite in second case also.
using (FileStream fs = new FileStream("Report.html", FileMode.Create, FileAccess.Write))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine(html);
}
}

To append to the end of your file:
File.AppendAllText("Report.html", html, Encoding.UTF8);
To overwrite your file:
File.WriteAllText("Report.html", html, Encoding.UTF8);

Try explicitly closing the writer and stream instead of depending upon you using () expression to do that for you.

Related

ArgumentException in StreamWriter in Xamarin.Forms

I am writing a Xamarin.Form PLC for Android and iOS, and have a place where I need to write some application stuff to a text file embedded resource. I've implemented reading from the same text file successfully, with same syntax just using StreamReader, but the StreamWriter implementation looks like this:
Assembly assembly = GetType().GetTypeInfo().Assembly;
string resource = "jetStream.Results.settings.txt";
using (Stream stream = assembly.GetManifestResourceStream(resource)) {
using (StreamWriter writer = new StreamWriter(stream)) {
//do stuff
}
}
StreamWriter is throwing an argument of "Stream is not writeable" at System.IO.StreamWriter. Am I doing something obvsiously wrong? Why is the Stream Readable but not Writeable using the same assembly/resource/stream construction?
The stream from GetManifestResourceStream is not writable. The stream's file is embedded in the assembly at build time and cannot be changed. You'll have to write the file to disk before you can write to it.
string resource = "jetStream.Results.settings.txt";
using (Stream stream = assembly.GetManifestResourceStream(resource))
using (var fs = new FileStream(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal)), FileMode.Create, FileAccess.Write))
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(fs))
{
rStream.Stream.CopyTo(stream);
writer.Write(stream.ToArray());
}
After this you can read and write to the file on disk.
Depending on what you want to write, if it's just things like application settings, you can use the Application.Properties collection http://www.kymphillpotts.com/exploring-xamarin-forms-1-3-properties-dictionary/ otherwise I agree with Jon's answer.

Create and write file txt

How can I create and then modify writing on this file?
string fileName = #"C:\...\MioFile.txt";
In main:
File.CreateText(fileName);
Then when I would edit the file by adding text.
StreamWriter writer = new StreamWriter(fileName);
sw.WriteLine("Hello"+variable);
sw.Close();
But the file is empty and I cannot write anything.
I would like create a file.txt and I would like for this file to always add new information every time I call it in writing mode. A kind of "log file".
Use File.AppendAllText instead of StreamWriter. Its simple:
File.AppendAllText(filename, "Hello"+variable);
You have sw.WriteLine, But your streamwriter is called "writer". That might be the problem.
I like to use the "using" statements:
//full path
var fileName = #"C:\Users\...\Desktop\newFile2.txt";
//Get the stream in FileMode.Append (will create or open)
using (var fileStream = new FileStream(fileName,FileMode.Append))
{
//pass the fileStream into the writer.
using (var writer = new StreamWriter(fileStream))
{
writer.WriteLine("{0} => file appended", DateTime.Now);
}//dispose writer
}//dispose fileStream

How to decompress with GZipStream in C#?

My problem is that I can't find a solution to decompress a file. Compressing a file works without error messages, but I don't know if that's right.
Here is my code for compressing a file:
using (StreamReader sr = new StreamReader(File.Open(srcFile, FileMode.Open), true))
using (GZipStream zip = new GZipStream(File.Open(destFile, FileMode.OpenOrCreate), CompressionMode.Compress, false))
using (StreamWriter sw = new StreamWriter(zip, Encoding.UTF8)) {
while (!sr.EndOfStream) {
sw.Write((char)sr.Read());
}
}
Then I tried to decompress the compressed file with following code:
using (GZipStream zip = new GZipStream(File.Open(srcFile, FileMode.Open), CompressionMode.Decompress, false))
using (StreamReader sr = new StreamReader(zip, true))
using (StreamWriter sw = new StreamWriter(File.Open(destFile, FileMode.OpenOrCreate), Encoding.UTF8)) {
while (!sr.EndOfStream) {
sw.Write((char)sr.Read());
}
}
The content of the decompressed file wasn't like the content of the source file and I don't know where I've made my mistakes.
Thanks in advance for your help.
I'm sorry for my bad English, but English isn't my strength. :/
Using StreamReader/Writer is not indicated. It will certainly destroy the file content if the file is not a text file. And the decompressed file will always have a BOM, it might be missing in the original file.
There's just no reason to use these classes, GZipStream doesn't care. Use FileStream instead, the only way to be sure that the decompressed bytes are an exact match with the bytes in the original file.

One program writes to file while other program reads same file c#

1) I have created a program that has opened a twitter stream and writes everything to a file.
FileStream fs = new FileStream(#"\Database\twitterstream.txt", FileMode.Create);
TextWriter tmp = Console.Out;
StreamWriter sw = new StreamWriter(fs);
Console.SetOut(sw);
2) I have another program that I want to read said text file.
using (StreamReader sr = File.OpenText("C:\\Database\\twitterstream.txt"))
{
input = sr.ReadLine();
}
Because I want it to be in real time I am trying to have one program write, while at the same time the other program reads, however obviously it is throwing
"The process cannot access the file
'C:\Database\twitterstream.txt' because it is being used by another
process" back at me.
Is what I am trying to do possible? If so, how do I go about doing it?
Add a couple parameters to you FileStream constructor:
FileStream fs = new FileStream(
#"\Database\twitterstream.txt",
FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
See FileStream on MSDN

StreamWriter.Write doesn't write to file; no exception thrown

My code in C# (asp.net MVC)
StreamWriter tw = new StreamWriter("C:\\mycode\\myapp\\logs\\log.txt");
// write a line of text to the file
tw.Write("test");
The file is created but is empty. No exception is thrown. I have never seen this before and I am stuck here; I just need to write some debugging output.
Please advise.
StreamWriter is buffered by default, meaning it won't output until it receives a Flush() or Close() call.
You can change that by setting the AutoFlush property, if you want to. Otherwise, just do:
StreamWriter tw = new StreamWriter("C:\\mycode\\myapp\\logs\\log.txt");
// write a line of text to the file
tw.Write("test");
tw.Close(); //or tw.Flush();
You need to either close or flush the StreamWriter after finishing writing.
tw.Close();
or
tw.Flush();
But the best practice is to wrap the output code in a using statement, since StreamWriter implements IDisposable:
using (StreamWriter tw = new StreamWriter("C:\\mycode\\myapp\\logs\\log.txt")){
// write a line of text to the file
tw.Write("test");
}
Neither flushed nor closed nor disposed.
try this
using (StreamWriter tw = new StreamWriter(#"C:\mycode\myapp\logs\log.txt"))
{
// write a line of text to the file
tw.Write("test");
tw.Flush();
}
or my preference
using (FileStream fs = new FileStream( #"C:\mycode\myapp\logs\log.txt"
, FileMode.OpenOrCreate
, FileAccess.ReadWrite) )
{
StreamWriter tw = new StreamWriter(fs);
tw.Write("test");
tw.Flush();
}
Use
System.IO.File.WriteAllText(#"path\te.txt", "text");
FileStream fs = new FileStream("d:\\demo.txt", FileMode.CreateNew,
FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.ASCII);
int data;
sw.Write("HelloWorld");
sw.Close();
fs.Close();
The problem is when StreamWriter Object is created with reference of FileStream Object , SW object will be always expecting some data till SW object is Closed.
So After using sw.Close();
Your Opened File will get closed and get ready for showing Output.
Ya in VB.net this was not needed but it seems with CSharp you need a Writer.Flush call to force the write. Of course Writer.Close() would force the flush as well.
We can also set the AutoFlush Property of the StreamWriter instance:
sw.AutoFlush = true;
// Gets or sets a value indicating whether the StreamWriter
// will flush its buffer to the underlying stream after every
// call to StreamWriter.Write.
From: http://msdn.microsoft.com/en-us/library/system.io.streamwriter.autoflush(v=vs.110).aspx
an alternative
FileStream mystream = new FileStream("C:\\mycode\\myapp\\logs\\log.txt",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter tw = new StreamWriter(mystream);
tw.WriteLine("test");
tw.close();
Try to close the file or add \n to the line such as
tw.WriteLine("test");
tw.Close();

Categories