I am trying to reading a .txt file of C or D drive in a UWP application. It is ok, when I declare the local variable for file name in assets. But it\'s filed to read file from o
As Adam McMahon said, UWP apps are sandboxed apps and don't directly access files in the external environment. For file permissions, you can view this document.
Specific to the example you provided, you can use FileOpenPicker to select a text file and read the contents from the obtained StorageFile.
This example is for reference:
public async static Task<StorageFile> OpenLocalFile(params string[] types)
{
var picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
Regex typeReg = new Regex(@"^\.[a-zA-Z0-9]+$");
foreach (var type in types)
{
if (type == "*" || typeReg.IsMatch(type))
picker.FileTypeFilter.Add(type);
else
throw new InvalidCastException("Invalid extension");
}
var file = await picker.PickSingleFileAsync();
if (file != null)
return file;
else
return null;
}
Usage
var txtFile=await OpenLocalFile(".txt");
if(txtFile!=null)
{
var lines = FileIO.ReadLinesAsync(txtFile);
// ... Other code
}
Best regards.
You do not have permission to access the file from your C or D Drive. To do So
You need to copy the file to Project folder (Drag and Drop it your Project)
Then you can use this code to access file
Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("sample.txt");
if you want to select your file randomly then I would suggest you to use FilePicker
Click here
You're getting this exception because UWP is sandboxed and you don't have permission to access that location by default. See here for a full list of locations that you are able to access by default.
If you absolutely need higher level access to more locations then your only option is to use broadFileSystemAccess
(which is also referenced in the above link). This will be a fine option if you're sideloading, but if you're uploading the the app store then you're likely going to run into a tonne of issues.
Conclusion: It depends entirely on what your needs are but if the file is only going to be read/written by your app then the best option would be to copy it to your apps LocalFolder
.