Windows Phone 8.1 access file in Documents folder - c#

I'm new to windows phone development, and not using silverlight or WPF. I copy the file "links.txt" into my Windows Phone folder at "\Documents\" and I want to access and get the content in the file, but I'm getting back as access denied error. I click on Package.appxmanifest file then select "Capabilities" tab, but I don't see "Documents Library Access" for me to check it. As matter fact I don't see any "... Library Access" showing. Below is the code:
string fileName = "\\Documents\\links.txt";
string parentPath = ApplicationData.Current.LocalFolder.Path;
string filePath = Path.Combine(parentPath, fileName);
StorageFile file = await StorageFile.GetFileFromPathAsync(filePath);
Any suggestion how can I read the file? thanks.
Updates:
It seems the code above does not work, but when using the code below and change the folder to "Music" instead of "Documents" then check the Capabilities for "MusicLibrary", it's working.
var folder = KnownFolders.MusicLibrary;
var file = await folder.GetFileAsync("links.txt");
var read = await FileIO.ReadTextAsync(file);
Thanks!

You are give the wrong filePath actual path is in this image
i try your code it shows same error so correct your file path

If you checked need Capability for Documents you should use KnownFolders class instead ApplicationData.Current.LocalFolder.Path.
For example:
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
StorageFile file = await storageFolder.CreateFileAsync("sample.dat", CreationCollisionOption.ReplaceExisting);

Related

Reading/Writing RichEditBox (.rtf) files without using picker (C# - Visual Studio - UWP)

I am struggling to create my first UWP program in C#. I have run into a problem with reading/writing .rtf files and have not been able to work out a solution nor find one in the forums.
My program is an application for reading and writing a daily journal. The daily journal entries are displayed and edited in a RichEditBox. Next to the RichEditBox is a CalendarDatePicker.
When the CalendarDatePicker value changes, the program creates a file name based on the CalendarDatePicker date. For example, if the CalendarDatePicker's value was 7/22/2018, my program would turn that into the following file name: "2018_7_22.rtf" and then assign that to a string named fileName.
All of the above is working as desired. Here is the problem I am having:
When the value of the CalendarDatePicker changes, the program is supposed to immediately load the .rtf file (if it exists) from storage into the RichEditBox. And, when I press the SAVE button, the program is
supposed to save the RichEditBox contents to storage. Both reading and writing the file is supposed to
use the name derived from the CalendarDatePicker value rather than opening up a picker for either
opening or saving the file.
I have not been able to find any documentation about how to read and write a .rtf file for the RichEditBox without using a picker. I do not want to use a picker because I want that the given journal entry can only be read or written according to the file name that is based on the current value of the CalendarDatePicker.
Here is what I am trying to do:
String filePath = Windows.Storage.ApplicationData.Current.LocalFolder.toString;
// this returns error: "cannot convert method group 'ToString' to non-delegate type string"
String fileName = "2018_22_7.rtf"
// this is an example of a string my program would create according to the CalendarDatePicker's value.
At the end of my question is the code from the RichEditBox documentation. I want do away with the portion that uses the picker and replace the following line:
Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();
with:
Windows.Storage.StorageFile file = filePath + fileName;
Is it possible to do this or am I forced to use a picker with the RichEditBox?
I will deeply appreciate any help I can get in solving this problem. I am
melting from frustration! Thank you!
Here is the code from the RichEditBox documentation:
private async void SaveButton_Click(object sender, RoutedEventArgs e)
{
Windows.Storage.Pickers.FileSavePicker savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Rich Text", new List<string>() { ".rtf" });
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "New Document";
Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
// Prevent updates to the remote version of the file until we
// finish making changes and call CompleteUpdatesAsync.
Windows.Storage.CachedFileManager.DeferUpdates(file);
// write to file
Windows.Storage.Streams.IRandomAccessStream randAccStream =
await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
editor.Document.SaveToStream(Windows.UI.Text.TextGetOptions.FormatRtf, randAccStream);
// Let Windows know that we're finished changing the file so the
// other app can update the remote version of the file.
Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);
if (status != Windows.Storage.Provider.FileUpdateStatus.Complete)
{
Windows.UI.Popups.MessageDialog errorBox =
new Windows.UI.Popups.MessageDialog("File " + file.Name + " couldn't be saved.");
await errorBox.ShowAsync();
}
}
}
Universal Windows Apps (apps) can access certain file system locations by default.
Before window version 17134, if you don't want use a picker to access the file, your UWP app only can access the files in the Application install directory, Application data locations, Removable devices and some Locations that UWP apps can access with specific Capability such as the Music and Pictures Libraries. But you can not write into the Application install directory. In this case, you can try to save the file in above location except the Application install directory. Such as the Application data locations then you can create and get the file using the following code. Please see the File access permissions for more details.
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
//Createa file
StorageFile fileToSave = await localFolder.CreateFileAsync("YourFileName");
//Get file
StorageFile file = await localFolder.GetFileAsync("YourFileName");
If your app target on version 17134 and later, you can access all files that the user has access to using the broadFileSystemAccess Capability, this capability works for APIs in the Windows.Storage namespace, you can get the file using the path as following code, here is a sample.
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(path);

Access file from the app folder in uwp

Directory:
App1
- MainPage.xaml.cs
- Sample.xaml
im trying to do is getting the xaml content from the sample as a string but it doesnt work since it cant find the file:
var x = Path.GetFullPath(#"sample.xaml");
FileStream s = new FileStream(x, FileMode.Open);
How can I fix this?
I haven't tried this give it a try.
Save your file in a location eg (Assets Folder)Now, make sure that the
build action is set to Content.
var storageFile = await StorageFile.GetFileFromApplicationUriAsync(
new Uri("ms-appx:///Assets/youfile.xaml"));
The StorageFile you get is of course read-only, but it can be passed to any API that expects a StorageFile.
If you want to read you can try.
var result = storageFile.OpenReadAsync()
StorageFile Documentation
The source files (.xaml, .cs) are compiled, and in the deployed app they do not exist as physical files, so you can't open them this way.

Error: "'FileName.docx" has been damaged and can't be opened'" in Windows Phone 8.1

I am trying to open documents but getting error. How do I resolve it?
This is headache for me, Any kind of document is not opening in my application.
I am trying to open PDF file using "PDF Reader" but getting error like this:
"Unable to Open"
Please suggest me.
See my code below.
string file = "test.docx";
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
if (isf.FileExists(file))
{
isf.DeleteFile(file);
}
var filerun = await ApplicationData.Current.LocalFolder.CreateFileAsync(file);
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile fileopen = await folder.GetFileAsync(file);
await Launcher.LaunchFileAsync(fileopen);
It seems that you are creating a totaly empty file and then try to open it with Word or PDFReader.
On Windows Phone you cannot open with Word an emty file just named filename.docx - try to create on computer a textfile file.txt, rename it to file.docx, copy to your phone, and then open via Files App - it won't work.
File extension only helps to determine the file type, but the most important is what is inside the file.
You should be able to open for example a file created with Word. Here is a sample example how I've done it - add a docx file (created for example on computer with Word) to your solution and change its Build Action to Content. Then try to open it like this:
private async void firstBtn_Click(object sender, RoutedEventArgs e)
{
StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFile file = await folder.GetFileAsync("sample.docx");
await Launcher.LaunchFileAsync(file);
}
As I've tried - should work without problems. If you encounter some, here is a working sample.
Nothing also stands on your way to prepare some empty docx templates and then inside the app just copy as new files and open them. You may also try to find an API to create Office files.

Save changes in file in Windows Store app in required directory

using c#, VS2013, windows store app
In simple program have a file with some data saved in JSON format. I'll try to add new data to this file and then store it.
Try to save file in JSON with next code:
string result = await JsonConvert.SerializeObjectAsync(groups);
//get file path
string pathOfFile = Path.GetDirectoryName(file.Path); //get path
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(pathOfFile); //create dir by path
StringBuilder builder = new StringBuilder();
builder.Append(folder.Path);
builder.Append("\\EventsData.json");
Uri uriToSave = new Uri(builder.ToString());
//create file
StorageFile fileToWrite =
await StorageFile.GetFileFromApplicationUriAsync(uriToSave);
using (IRandomAccessStream stream =
await file.OpenAsync(FileAccessMode.ReadWrite))
{
// write the JSON file
using (DataWriter textWriter = new DataWriter(stream))
{
textWriter.WriteString(result);
await textWriter.StoreAsync();
}
}
But during executing code StorageFile fileToWrite = await StorageFile.GetFileFromApplicationUriAsync(uriToSave); got exception System.ArgumentException
During debagging got next Uri
Question - why i got such exception and if I'm wrong - how to save file in windows store app in required directory?
Also look MSDN sample for writing data to file, and use code like in tutorial but got System.UnauthorizedAccessException:
StorageFile sampleFile = await folder.CreateFileAsync("EventsData.json", CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteTextAsync(sampleFile, result);
Why Access denied or I missing something?
You cannot write to the install directory without explicit permission from the user.
Here is the protocol instead:
At first startup, check to see if there is a file in the local data folder (ApplicationDataContainer), if not, read in the file from the install directory.
Write out a copy of the file to the local app data folder (Check out guides on ApplicationDataContainer for more info there)
Edit this file freely.

Windows metro apps - write and read text files in C#?

creating text file:
var myFile = "test";
var folderUsed = Windows.Storage.ApplicationData.Current.LocalFolder;
var fileOption = Windows.Storage.CreationCollisionOption.ReplaceExisting;
var createdFile = await folderUsed.CreateFileAsync(myFile, fileOption);
writing a string into created text file:
var writeThis = "write this ";
await Windows.Storage.FileIO.WriteTextAsync(createdFile, writeThis);
However, it doesn't specify in which part the text file will be created, I'd like to create it inside the package of my app, not in somewhere else in my computer, is it possible?
And secondly, when I execute the second code again, I'd like my file to be written as "write this write this ", not replace the old file and create another one.
You should use
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
since the other folders such as installation folders are restricted and not allowed for read-write operations. Windows Store apps are pretty restricted in this area.
This link is also useful:
http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh758325.aspx
If your files are in the assets folder then you can access them by:
String path = "ms-appx:///Assets/" + Domain + ".txt";
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(path));
string Value = await FileIO.ReadTextAsync(file);
"However, it doesn't specify in which part the text file will be created, I'd like to create it inside the package of my app, not in somewhere else in my computer, is it possible?"
It's actually 'almost' the only thing possible! your application has explicit access to it's own 'LocalFolder' folder, 'RoamingFolder' location which can be shared between application instances or 'TemporaryFolder' for stuff which gets ditched.
You can save files to thing like pictures library using Windows.Storage.KnownFolders.pictureLibrary if you want, and you can get read only access to your installation folder using 'Windows.ApplicationModel.Package.current.installedLocation' if you so wish.

Categories

Resources