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);
}
Related
I need to save the file when method OnDestroy is called and load same file when method OnCreate is called. At this time I can read json file easily from Assets (this works fine)
StreamReader reader = new StreamReader(Assets.Open("reiksmes.json"));
string JSONstring = reader.ReadToEnd();
Daiktai myList = JsonConvert.DeserializeObject<Daiktai>(JSONstring);
items.Add(myList);
, but I have some problems when I try to save(write) Daiktai class data to the same file I opened above. I tried:
string data = JsonConvert.SerializeObject(items);
File.WriteAllText("Assets\\reiksmes.json", data);
with this try I get error System.UnauthorizedAccessException: Access to the path "/Assets
eiksmes.json" is denied.
also tried:
string data = JsonConvert.SerializeObject(items);
StreamWriter writer = new StreamWriter(Assets.Open("reiksmes.json"));
writer.WriteLine(data);
and with this try I get error System.ArgumentException: Stream was not writable.
Summary:
I think I chose bad directory(Assets), I need to save and load data (json format). So where do I need to save them and how(give example)?
You can't save anything to assets. You can just read from it. You have to save the file to a different folder.
var fileName = "reiksmes.json";
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, fileName);
Console.WriteLine(path);
if (!File.Exists(path))
{
var s = AssetManager.Open(fileName);
// create a write stream
FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
// write to the stream
ReadWriteStream(s, writeStream);
}
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 data from json file in .NET 4.5 for Windows Phone app. After pressing button the exception appears saying:
System.IO.FileNotFoundException (Exception from HRESULT: 0x80070002)
My code:
public static async Task ReadFile()
{
StorageFolder local = Windows.ApplicationModel.Package.Current.InstalledLocation;
if (local != null)
{
var file = await local.OpenStreamForReadAsync("bazaDanych.json");
using (StreamReader streamReader = new StreamReader(file))
{
json = streamReader.ReadToEnd();
}
}
}
Here's my view of Solution Explorer:
You're not copying your file to the local storage.
Put your json file under the Assets folder, make sure that it's properties says "Content" and "Copy Always"
On the first launch you should read the json from the package
var filename = "Assets/BazaDanych.json";
var sFile = await StorageFile.GetFileFromPathAsync(filename);
var fileStream = await sFile.OpenStreamForReadAsync();
And store into the local storage.
There is an example for Windows 8 (which is more or less the same)
Related question.
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 have a file, which the users browse and hit the upload button, i save the file on the server, appdata/uploads in the application directory. then i try to read it using stream reader and then parse it. on my local development enviornment it works fine, but when i deploy it on a server it does not work at all. any suggestions?? thank you
//Save LoadList File:
DateTime uploadDate = DateTime.Now;
string destinationPath = string.Format("{0}\\{1}\\{2}\\{3}\\", Server.MapPath("~/App_Data/uploads"), uploadDate.ToString("yyyy"), uploadDate.ToString("MMM"), uploadDate.ToString("dd"));
if (!Directory.Exists(destinationPath))
Directory.CreateDirectory(destinationPath);
string storedFileName = string.Format("{0}{1}.json", destinationPath, System.Guid.NewGuid());
file.ElementAt(0).SaveAs(storedFileName);
//FileImport is a static class
var Pair = FileImport.CyclesCompleted(storedFileName);
private static string LoadTextFromFile(string fileName)
{
StreamReader streamReader = new StreamReader(fileName);
string text = streamReader.ReadToEnd();
streamReader.Close();
return text;
}
Saving file on server ususlly results in permission errors since most accounts can't write to default location on server. You may get away with using Path.GetTempFileName, but even in this case some accounts (i.e. account that requests run for "anonymous user") will not have permissions to read/write to that location.
If you simply need to parse uploaded file you can copy stream to MemoryStream and create StreamReader over this memory stream. You may be able to use Stream for uploaded file directly, but it will not support seaking (may work as you are using StreamReader which does not seek).