In windows phone 8.1
i want to use streamwriter in text, and appending text to file end.
But the text is appended to the beginning of the file.
how to appending text to file end?
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(#"ms-appx:///input_category_list.txt"));
using (StreamWriter sWrite = new StreamWriter(await file.OpenStreamForWriteAsync(), System.Text.UTF8Encoding.UTF8))
{
sWrite.WriteLine(write_category_box.Text);
await sWrite.FlushAsync();
}
There's no need for StreamWriter in Windows Runtime, you can use FileIO class (which is easier):
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(#"ms-appx:///input_category_list.txt"));
await FileIO.AppendTextAsync(file, write_category_box.Text, UnicodeEncoding.Utf8);
change your code to this:
new StreamWriter(await file.OpenStreamForWriteAsync(),System.Text.UTF8Encoding.UTF8,true))
if you overrride StreamWriter constructor, as true, this will set to append text. Otherwise overwrite it.
Related
I'm trying to keep track of some information by using a text file. I want the text file to reset every time I write in it so that I don't get a bunch of old information. Is there any way for me to do this?
void WriteString(string text, string path) {
StreamWriter writer = new StreamWriter(path, true);
writer.Write(text);
writer.Close();
}
If you change "true" to "false" in the constructor call, it will overwrite the file.
StreamWriter writer = new StreamWriter(path, false);
// Your Text File Path
string path = #"";
// The Text You Want To Write inside The File
string content = "";
// This Method Clears Whatever Text It Finds in the File and Writes the new Content (overwrites the text file)
File.WriteAllText(path, content);
I want to be able to have a list of class objects (List<Class>) and be able to easily write and read to a text file.
In my older Console Applications and Windows Forms applications I used to use:
List<Class> _myList = ...
WriteToFile<List<Class>>("C:\\...\\Test.txt", Class _myList)
public static void WriteToFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var serializer = new XmlSerializer(typeof(T));
writer = new StreamWriter(filePath, append);
serializer.Serialize(writer, objectToWrite);
}
finally
{
if (writer != null)
writer.Close();
}
}
However this does not work in a UWP application and I have to use StorageFolder and StorageFile which works fine for writing simple text to a file like this:
StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile file= await storageFolder.GetFileAsync("Test.txt");
await FileIO.WriteTextAsync(sampleFile, "Example Write Text");
But I want to be able to use the more advanced functionality of XmlSerializer along with StreamWriter to write lists of classes to a file within my UWP application.
How can I do this?
You can use the Stream-based versions the methods you use, for example StreamWriter has a constructor which takes a System.IO.Stream instance.
To get a System.IO.Stream from a StorageFile, you can use the OpenStreamForWriteAsync and OpenStreamForReadAsync extension methods, which are in the System.IO namespace on UWP:
//add to the top of the file
using System.IO;
//in your code
var stream = await myStorageFile.OpenStreamForWriteAsync();
//do something, e.g.
var streamWriter = new StreamWriter(stream);
I am looking for a way to append strings-text to a file in a Windows Store App. I have tried reading the file and then creating a new one to overwrite it but Windows Store Apps C# does not work like C where when creating a new file with the same name overwrites the old one. Currently my code is opening the old file, reading it's contents, deleting it and creating a new one with the content I read plus the content I wish to append.
I know there is a better way but I cannot seem to find it. So How may I append text to an already existent file in a Windows Store App (Windows RT)?
EDIT--
I tried this
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var file = await folder.GetFileAsync("feedlist.txt");
await Windows.Storage.FileIO.AppendTextAsync(file, s);
but I keep getting System.UnauthorizedAccessException
according to MSDN this happens when the file is readonly (I checked with right click properties, it's not) and if I do not have the necessary privileges to access the file
what should I do?
You can use the FileIO class to append to a file. For example ...
// Create a file in local storage
var folder = ApplicationData.Current.LocalFolder;
var file = await folder.CreateFileAsync("temp.txt", CreationCollisionOption.FailIfExists);
// Write some content to the file
await FileIO.WriteTextAsync(file, "some contents");
// Append additional content
await FileIO.AppendTextAsync(file, "some more text");
Check out the File Access Sample for more examples.
Using FileIO.AppendTextAsync is a good option.
Please find the code snippet for this.
First it creates a folder, if not exists. Otherwise it will not create.
Then it creates a file if not exists.
Finally appending the text in the file.
public static async void WriteTrace(TraceEventType eventType, string msg, [CallerMemberName] string methodName = "")
{
const string TEXT_FILE_NAME = "Trace.txt";
string logMessage = eventType.ToString() + "\t" + methodName + "\t" + msg ;
IEnumerable<string> lines = new List<string>() { logMessage };
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
//if(localFolder.CreateFolderQuery(Windows.Storage.Search.CommonFolderQuery.)
StorageFolder LogFolder = await localFolder.CreateFolderAsync("LogFiles", CreationCollisionOption.OpenIfExists);
await LogFolder.CreateFileAsync(TEXT_FILE_NAME, CreationCollisionOption.OpenIfExists);
StorageFile logFile = await LogFolder.GetFileAsync(TEXT_FILE_NAME);
await FileIO.AppendLinesAsync(logFile, lines);
}
I would like to ask how i can change file content on OneDrive. I'm using OneDrive SDK and when I'm trying change file Name it is working, but with Content I'm getting this error "Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.
Here is my code - I'm just parsing string to stream...
StreamWriter writer = new StreamWriter(stream);
writer.Write("Hello word");
writer.Flush();
stream.Position = 0;
var updateItem = new Item { Name = txtNazev.Text+".txt", Content = stream };
var itemWithUpdates = await oneDriveClient
.Drive
.Items[Id]
.Request()
.UpdateAsync(updateItem);
You'll want to access the Content property before calling Request(), and then use PutAsync<Item> instead of UpdateAsync.
Take a look at this documentation for an example (note that it's a little different as it's accessing the item by path, but everything after that will be what you want).
I am looking for a way to append strings-text to a file in a Windows Store App. I have tried reading the file and then creating a new one to overwrite it but Windows Store Apps C# does not work like C where when creating a new file with the same name overwrites the old one. Currently my code is opening the old file, reading it's contents, deleting it and creating a new one with the content I read plus the content I wish to append.
I know there is a better way but I cannot seem to find it. So How may I append text to an already existent file in a Windows Store App (Windows RT)?
EDIT--
I tried this
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var file = await folder.GetFileAsync("feedlist.txt");
await Windows.Storage.FileIO.AppendTextAsync(file, s);
but I keep getting System.UnauthorizedAccessException
according to MSDN this happens when the file is readonly (I checked with right click properties, it's not) and if I do not have the necessary privileges to access the file
what should I do?
You can use the FileIO class to append to a file. For example ...
// Create a file in local storage
var folder = ApplicationData.Current.LocalFolder;
var file = await folder.CreateFileAsync("temp.txt", CreationCollisionOption.FailIfExists);
// Write some content to the file
await FileIO.WriteTextAsync(file, "some contents");
// Append additional content
await FileIO.AppendTextAsync(file, "some more text");
Check out the File Access Sample for more examples.
Using FileIO.AppendTextAsync is a good option.
Please find the code snippet for this.
First it creates a folder, if not exists. Otherwise it will not create.
Then it creates a file if not exists.
Finally appending the text in the file.
public static async void WriteTrace(TraceEventType eventType, string msg, [CallerMemberName] string methodName = "")
{
const string TEXT_FILE_NAME = "Trace.txt";
string logMessage = eventType.ToString() + "\t" + methodName + "\t" + msg ;
IEnumerable<string> lines = new List<string>() { logMessage };
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
//if(localFolder.CreateFolderQuery(Windows.Storage.Search.CommonFolderQuery.)
StorageFolder LogFolder = await localFolder.CreateFolderAsync("LogFiles", CreationCollisionOption.OpenIfExists);
await LogFolder.CreateFileAsync(TEXT_FILE_NAME, CreationCollisionOption.OpenIfExists);
StorageFile logFile = await LogFolder.GetFileAsync(TEXT_FILE_NAME);
await FileIO.AppendLinesAsync(logFile, lines);
}