Here is a snippet of the code I'm having issues with:
public OpenPage(string filePath, int? index, object jobject)
{
InitializeComponent();
File.SetAttributes(filePath, FileAttributes.Normal); // Here is where error in title occurs
var readText = File.ReadAllText(filePath); // Also occurs here
DisplayAlert("Alert", readText, "Ok");
}
I'm creating a UWP Xamarin.Forms application which needs to read a file from a selected directory (anything on the C: drive). Although I'm getting the error in the title when I don't choose files from the local cache / AppData.
Looking at other similar posts in StackOverflow (such as Why is access to the path denied?) was great for learning more about the subject, although many questions regarding this error are outdated.
In the post above, one person said that a directory cannot be passed as File.ReadAllText()'s parameter.
Is there any work around to this? I need access to files on the C: drive. For reference, the filePath in the constructor when I was debugging was ""C:\Users\ianpc\Desktop\config file clones\te0_ptt_wog.json".
Is there any work around to this? I need access to files on the C: drive. For reference, the filePath in the constructor when I was debugging was ""C:\Users\ianpc\Desktop\config file clones\te0_ptt_wog.json".
The problem is UWP app runs in sandbox environment, so we can't use System.IO
namespace to access file with path directly.
For xamarin forms app, we suggest you use Windows Storage api to access file with path and before that, you need enable broadFileSystemAccess
capability.
For example
public interface FileAccessInterface
{
Task<string> GetFileText(string filePath);
}
Implementation
[assembly: Dependency(typeof(FileAccessInterfaceImplementation))]
namespace XamarinPicker.UWP
{
public class FileAccessInterfaceImplementation : FileAccessInterface
{
public async Task<string> GetFileText(string filePath)
{
var stringContent = "";
try
{
var file = await StorageFile.GetFileFromPathAsync(filePath);
if (file != null)
{
stringContent = await Windows.Storage.FileIO.ReadTextAsync(file,Windows.Storage.Streams.UnicodeEncoding.Utf8);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return stringContent;
}
}
}
Usage
var text = await DependencyService.Get<FileAccessInterface>().GetFileText(@"C:\Users\xxxx\Desktop\test.txt");
For more please refer this case reply.