ArgumentException in StreamWriter in Xamarin.Forms - c#

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.

Related

Overwriting file in c# using stream writer

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.

Working with .tmp file for writing data

I'm wondering if there is a best practice when it comes to working with .tmp file for writing data. I like to make an .tmp that will be use in the filestream and then when I close the writer, I like to rename the file. Is there a way to rename file extension?
FileStream stream2 = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
StreamWriter streamWriter2 = new StreamWriter(stream2);
streamWriter2.WriteLine(textToAdd);
streamWriter2.Close();
string changed = Path.ChangeExtension(fileName, .txt);
File.Move(path, changed);
Here's how I would do this:
// Build a FileInfo object for your temp destination, this gives us
// access to a handful of useful file manipulation methods
var yourFile = new FileInfo(#"C:\temp\testfile.tmp");
// open a StreamWriter to write text to the file
using (StreamWriter sw = yourFile.CreateText())
{
// Write your text
sw.WriteLine("Test");
// There's no need to call Close() when you're using usings
}
// "Rename" the file -- this is the fastest way in C#
yourFile.MoveTo(#"C:\temp\testfile.txt");
You can use Path.GetFilenameWithoutExtension to remove the extension and then just add the one you want.

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.

Why is the resource stream always null?

Hopefully something simple but have tried and tried and keep failing.
I am attempting to create a Stream object in a C# application that will copy a CSS file to a specific location.
The CSS file is embedded in my resources.
Regardles of what I have tried the stream object is always null.
Can somebody please point in the right direction by looking at the below?
Thanks :) burrows111
Assembly Assemb = Assembly.GetExecutingAssembly();
Stream stream = Assemb.GetManifestResourceStream(ThisNameSpace.Properties.Resources.ClockingsMapStyle); // NULL!!!!
FileStream fs = new FileStream("to store in this location", FileMode.Create);
StreamReader Reader = new StreamReader(stream);
StreamWriter Writer = new StreamWriter(fs);
Writer.Write(Reader.ReadToEnd());
This works for me:
StreamReader reader;
StreamWriter writer;
Stream stream;
Assembly assembly = Assembly.GetExecutingAssembly();
using (stream = assembly.GetManifestResourceStream("Namespace.Stylesheet1.css"))
using (reader = new StreamReader(stream))
using (writer = new StreamWriter("test.css"))
{
string content = reader.ReadToEnd();
writer.Write(content);
writer.Close();
}
I tried it in a standard Windows Forms app.
EDIT: The file (Stylesheet1.css) was included as a normal item in the project with a build action of "Embedded Resource".

Rename File in IsolatedStorage

I need to rename a file in the IsolatedStorage. How can I do that?
There doesn't appear to anyway in native C# to do it (there might be in native Win32, but I don't know).
What you could do is open the existing file and copy it to a new file and delete the old one. It would be slow compared to a move, but it might be only way.
var oldName = "file.old"; var newName = "file.new";
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var readStream = new IsolatedStorageFileStream(oldName, FileMode.Open, store))
using (var writeStream = new IsolatedStorageFileStream(newName, FileMode.Create, store))
using (var reader = new StreamReader(readStream))
using (var writer = new StreamWriter(writeStream))
{
writer.Write(reader.ReadToEnd());
}
In addition to the copy to a new file, then delete the old file method, starting with Silverlight 4 and .NET Framework v4, IsolatedStorageFile exposes MoveFile and MoveDirectory methods.
Perfectly execute this piece of code
string oldName="oldName";
string newName="newName";
var file = await ApplicationData.Current.LocalFolder.GetFileAsync(oldName);
await file.RenameAsync(newName);

Categories