When I call the following function, it should create a .txt file and write a sentence in it. It seems to execute without any errors. But I cannot find where this file is stored/located after being created. I ran a Windows Search to look for the file but nothing came up. Where is this file located? Also, what is the best folder/location to put a .txt file that the program uses? Should I put it in Solution Explorer of Visual Studio or Debug folder?
private async void CreateFile() {
try {
// Create sample file, replace if exists.
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile sampleFile = await storageFolder.CreateFileAsync("sample.txt", CreationCollisionOption.ReplaceExisting);
sampleFile = await storageFolder.GetFileAsync("sample.txt");
await FileIO.WriteTextAsync(sampleFile, "Swift as a shadow!");
} catch (Exception ex) {
textBox.Text = ex.ToString();
}
}
You can have the code show the path:
sampleFile = await storageFolder.GetFileAsync("sample.txt");
await new MessageDialog(sampleFile.Path).ShowAsync();
On Windows 10, this will be a path like:
C:\Users\[username]\AppData\Local\Packages\[Package family name]\LocalState\sample.txt
where username is the name of the logged on user and package family name is the package family name of your application
Related
I am facing an problem with files that I create within my application in dedicated sub folders of ApplicationData.Current.LocalFolder. I can create sub folders with ApplicationData.Current.LocalFolder.CreateFolderAsync() and even place files in it. But as soon as I try to overwrite or delete files, I get an access violation exception. (Read Access is still possible)
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
I looked up the UWP pages but most of the time they simply create a new folder and that's it.
My attempt to overwrite the file:
public async Task WriteFileAsync(string filename, Stream fileContent)
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
var deepFolders = filename.Split('/');
if (deepFolders != null)
{
for (var i=0; i<deepFolders.Length - 1; i++)
{
folder = await folder.GetFolderAsync(deepFolders[i]);
}
filename = deepFolders[deepFolders.Length - 1];
}
try
{
StorageFile oldFile = await folder.GetFileAsync(filename);
await oldFile.DeleteAsync();
}
catch (FileNotFoundException) { }
StorageFile file = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
}
The first time it runs just fine, but as soon as the overwrite should take place, I get the exception.
Running the whole stuff without sub-folders works like charm.
The attempt to first read and delete the file resulted in the same exception already during the deletion.
I need to save app files to plugged SD card. I'm using UWP and Windows 10.
MSDN tells how to do it with Windows Libraries.
var myPicsLibrary = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);
await myPicsLibrary.RequestAddFolderAsync();
RequestAddFolderAsync() shows file picker, where user can choose folder to add into Pictures. In my case it's a folder, created on SD card.
Is there a way to do this thing without file picker dialog?
I'm trying to do like this:
var myPicsLibrary = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);
// Get the logical root folder for all external storage devices.
StorageFolder externalDevices = Windows.Storage.KnownFolders.RemovableDevices;
// Get the first child folder, which represents the SD card.
StorageFolder sdCard = (await externalDevices.GetFoldersAsync()).FirstOrDefault();
var folder = await sdCard.CreateFolderAsync("MySDCardFolder");
myPicsLibrary.Folders.Insert(myDocs.Folders.Count+1, folder); // NotImplementedException: 'The method or operation is not implemented.'
myPicsLibrary.Folders.Add(folder); // NotImplementedException: 'The method or operation is not implemented.'
Or maybe I can do the same without using Windows Libraries directly working with SDCard?
Thanks a lot!
EDIT:
In the another hand my question sounds like "How to save files to plugged SD card?"
The StorageLibrary.Folders gets the folders in the current library, it return the IObservableVector of the StorageFolder. When we add the folder into the IObservableVector, it will not change the folder in files system. It will throw the "The method or operation is not implemented." exception.
We should be able to get the name of the folder, and create the folder uses that name. Then we can StorageFile.CopyAsync method to copy the file that in your folder.
For example:
public static async Task CopyFolderAsync(StorageFolder source, StorageFolder destinationContainer, string desiredName = null)
{
StorageFolder destinationFolder = null;
destinationFolder = await destinationContainer.CreateFolderAsync(
desiredName ?? source.Name, CreationCollisionOption.ReplaceExisting);
foreach (var file in await source.GetFilesAsync())
{
await file.CopyAsync(destinationFolder, file.Name, NameCollisionOption.ReplaceExisting);
}
foreach (var folder in await source.GetFoldersAsync())
{
await CopyFolderAsync(folder, destinationFolder);
}
}
Then we can use the CopyFolderAsync method to copy the folder in the Picture Library.
var myPicsLibrary = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);
var myfolder = myPicsLibrary.Folders[0];
StorageFolder externalDevices = Windows.Storage.KnownFolders.RemovableDevices;
StorageFolder sdCard = (await externalDevices.GetFoldersAsync()).FirstOrDefault();
var folder = await sdCard.CreateFolderAsync("MySDCardFolder");
await CopyFolderAsync(folder, myfolder);
As I get from your question you need to create a Folder in PicturesLibrary .
You can use the code below to add a folder into PicturesLibrary
await Windows.Storage.KnownFolders.PicturesLibrary.CreateFolderAsync("MySDCardFolder");
if you want to make it on SD Card only Maybe KnownFolders.RemovableDevices Should be helpful . I didn't used KnownFolders.RemovableDevices yet but if you have any issue let me know to test it on my phone directly
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 am having some issues in my app that can download a list of music files. I'm trying to setup the following folder structure. Music Library > Artist(s) > Release Name. When starting the download, the first song's folder structure is setup properly. Once the second download starts, I always get a File Not found exception when trying to create the second sub folder (release name). Here is my code.
private async Task StartDownload(List<DownloadData> data)
{
foreach (DownloadData song in data)
{
// Set the source of the download
Uri source = new Uri(song.downloadUrl);
// Create folder stucture
StorageFolder artistFolder;
try
{
artistFolder = await KnownFolders.MusicLibrary.CreateFolderAsync(song.artistName, CreationCollisionOption.OpenIfExists);
}
catch
{
throw;
}
StorageFolder releaseFolder;
try
{
releaseFolder = await artistFolder.CreateFolderAsync(song.releaseName, CreationCollisionOption.OpenIfExists);
}
catch
{
throw; // Exception Thrown here
}
// Create file
StorageFile destinationFile;
try
{
destinationFile = await releaseFolder.CreateFileAsync(song.fileName, CreationCollisionOption.GenerateUniqueName);
}
catch
{
throw;
}
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(source, destinationFile);
List<DownloadOperation> requestOperations = new List<DownloadOperation>();
requestOperations.Add(download);
await HandleDownloadAsync(download, true);
}
}
I have no idea why it works the first time around but fails on the second song.
According to the documentation for CreateFileAsync it will throw FileNotFoundExcption if
The folder name contains invalid characters, or the format of the folder name is incorrect.
So you likely need to replace invalid characters with something else like underscore.
var fixedFolderName = string.Join(
"_",
song.releaseName.Split(Path.GetInvaildFileNameChars()));
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);
}