I am currently writing a language translator application. I want to support the ability to choose a file, read in the contents of the file into the entry box, and output the translation once the appropriate button is pressed.
I am using the plugin 'Xam.Plugin.FilePicker' to allow the user to choose a file, which is working. When the user chooses a file, I have it so that the name of the file is displayed on the screen. However, problems occur when trying to read in the file into the entry box, which I believe is linked to the application not being able to determine the path of the file - currently the application tries to read in the file from the location where Visual Studio 2017 is located.
I have tried several approaches, some of which are detailed in the below:
I have also tried:
var file = await CrossFilePicker.Current.PickFile();
if (file != null) {
string filePath =
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string filename = Path.Combine(filePath, file.FileName);
using (var reader = new StreamReader(filename)) {
entText= reader.ReadToEnd();
}
}
Where entText
is the name of the entry box in the MainPage.xaml.cs file
Below is the code I have so far. I have removed the above code from the file and, while it was giving me a path, the path was either the path in which Visual Studio 2017 is located in or some other path. Either way, the application couldn't find the file.
C# code:
private async void BtnReadFile_Clicked(object sender, EventArgs e)
{
string fileName;
string fileText;
string filePath;
// Allows the user to choose a file from any location
var file = await CrossFilePicker.Current.PickFile();
if (file != null)
{
lblFileRead.Text = file.FileName; // Displays the name of the file
}
}
Xaml code:
- Entry box:
<Entry x:Name="entText" Placeholder="Enter text to translate" Keyboard="Text"
HeightRequest="200" WidthRequest="250" TextChanged="EntText_TextChanged" />
- Button to read in file
<Button x:Name="btnReadFile" Text="Read in file" Clicked="BtnReadFile_Clicked" />
To conclude, I want to be able to read in a file from any location, not just a predetermined location i.e.
The user should be able to read in a file from "C:/Documents/files", "C:/Downloads/", etc.