I have problem with save xml in local folder.
I use their variable.
SelectFile is properites with name file ( for example goal.xml or goal(1).xml etc.)
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync(SelectFile);
XDocument document = XDocument.Load(storageFile.Path);
XDocument document = XDocument.Load(storageFile.Path);
This document load good, but load document, not save.
var elementStepOne = document.Elements("StepOne").Single();
elementStepOne.Value = "delete content";
document.Save(SelectFile); // in line I try other mean write.
How I save this document? I want edit this document and save.
There are probably many ways to do this. One way is to use a file stream to save the xml:
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync(SelectFile);
XDocument document = XDocument.Load(storageFile.Path);
var elementStepOne = document.Elements("StepOne").Single();
elementStepOne.Value = "delete content";
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
SelectFile,
CreationCollisionOption.ReplaceExisting);
using (var writeStream = await file.OpenStreamForWriteAsync())
{
document.Save(writeStream);
}
Related
I'm trying to save my text file in UWP, but It always saving to different file. By the way I'm using MVVM architecture.
My Code
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedFileName = "New Text Document";
savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
savePicker.FileTypeChoices.Add("Text Document", new List<string>() { ".txt" });
savePicker.DefaultFileExtension = ".txt";
StorageFile storageFile = await savePicker.PickSaveFileAsync();
if(storageFile != null)
{
CachedFileManager.DeferUpdates(storageFile);
await FileIO.WriteTextAsync(storageFile, Document.Text);
FileUpdateStatus updateStatus = await CachedFileManager.CompleteUpdatesAsync(storageFile);
Document.FileName = savePicker.SuggestedFileName;
Document.IsSaved = true;
}
My code is always saving texts on different file. I'm trying to save my text to same file.
In UWP there is a feature called FutureAccessList. It can be used to save the token of the file, opened with the FilePicker. When you now want to save it again you can retrive the StorageFile by the token and write to it.
Add a FileToken property to your Document class:
public string FileToken { get; set; }
Now when you pick your file you add the file to the FutureAccessList:
...
StorageFile storageFile = await savePicker.PickSaveFileAsync();
if (storageFile != null)
{
CachedFileManager.DeferUpdates(storageFile);
await FileIO.WriteTextAsync(storageFile, Document.Text);
FileUpdateStatus updateStatus = await CachedFileManager.CompleteUpdatesAsync(storageFile);
Document.FileName = savePicker.SuggestedFileName;
Document.IsSaved = true;
//Add the file to the FutureAccessList to get it back later
Document.FileToken = StorageApplicationPermissions.FutureAccessList.Add(storageFile);
}
To retrive the file and save it again:
public async void SaveFile()
{
//Get the file back from the FutureAccessList by its token and write to it
StorageFile file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(Document.FileToken);
await FileIO.WriteTextAsync(file, Document.Text);
}
Now when you e.g. save your Document class to Json and retrive it after the app restarts you can still use the FileToken to write to the file. There is no need to let the user pick it again using the SaveFilePicker.
When the code above is to complicated or there is no need for this (I don't know what you need this for), you can put a StorageFile propertie directly to your Document class and put the file, that the SaveFilePicker returned in it. But this won't work when restarting the app. The user would always have to pick the file again.
My C# project saves some machine data in an XML file. I want to show this data in an HTML website in the network. I create the XML file like so:
StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(
"history.xml",
CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
System.IO.Stream s = writeStream.AsStreamForWrite();
XmlWriterSettings historyXMLwriterSettings = new XmlWriterSettings();
historyXMLwriterSettings.Indent = true;
historyXMLwriterSettings.IndentChars = " ";
historyXMLwriterSettings.CloseOutput = true;
historyXMLwriterSettings.Async = true;
XmlWriter historyXMLwriter = XmlWriter.Create(s, historyXMLwriterSettings);
XmlSerializer historyXMLserializer = new XmlSerializer(typeof(List<Auftrag>));
historyXMLserializer.Serialize(historyXMLwriter, auftragsliste);
await historyXMLwriter.FlushAsync();
}
My problem is that I need the file history.xml in the second project "webserver" in the public folder. How can I create the file directly in this folder or copy it?
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'm trying to read/write some text files from Local Storage:
KnownFolders.DocumentsLibrary
I have a simple text file that is stored in 'Documents' in my OneDrive folder, and I can read that fine. But when I write out another text file it gets created in my local 'Documents' folder for my PC, not the OneDrive folder. Why is that when I'm pointing to the same folder for both reading and writing, it reads from one location, but writes to another? Here is the method:
public static async void MyMethod()
{
var myFolder = KnownFolders.DocumentsLibrary;
Stream myStream = await myFolder.OpenStreamForReadAsync("readFromHere.txt");
string fileContents = "";
using (StreamReader streamReader = new StreamReader(myStream))
fileContents = streamReader.ReadToEnd();
var outputFile = await myFolder.CreateFileAsync("writeToHere.txt", CreationCollisionOption.OpenIfExists);
await FileIO.WriteTextAsync(outputFile, fileContents);
}
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);
}