如何使用 xamarin 保存文本文件以及文件保存在哪里

Tom*_*son 1 c# visual-studio-2010 xamarin

我是 Xamarin 的新手。我有简单的应用程序;我有笔记字段和拍照功能的地方。我正在使用媒体插件拍照。图片显然会保存在手机图库中。但我也想保存文本文件,其中包含手机中笔记字段的输入。

我正在努力保存文本文件。

是产品结构。我正在使用共享项目。

文件结构和类图像

示例应用程序图片

我有一个保存按钮。我想要做的是点击保存按钮时;保存用户从注释字段输入的文本文件。

这是我的保存按钮的操作

我在看这个网站 https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/files?tabs=windows

我尝试了一些代码,但没有任何效果。

private async void Take_Photo_Button_Clicked(object sender, EventArgs e)
{
    await CrossMedia.Current.Initialize();
    if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
    {
        await DisplayAlert("No Camera", ":( No camera available.", "OK");
        return;
    }

    var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
    {
        SaveToAlbum = true,
        Name = jobnoentry.Text + "-" + Applicationletterentry + "-" + signnoentry.Text + "-" + SignType,

    });


    if (file == null)
        return;

    MainImage.Source = ImageSource.FromStream(() =>
    {
        var stream = file.GetStream();
        return stream;
    });


    //Save text field 

    string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp.txt");
    File.WriteAllText(fileName, "Hello World");


}
Run Code Online (Sandbox Code Playgroud)

jgo*_*SFT 5

首先,文件的确切保存位置取决于平台,但您始终可以打印文件名的字符串以查看实际路径,例如

string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp.txt");
Console.WriteLine(filename); // will write the actual path to the application output.
Run Code Online (Sandbox Code Playgroud)

在任何情况下,您使用的路径Environment.SpecialFolder.LocalApplicationData, 都会将文本文件保存到只能由应用程序本身访问的位置,您不会在文件浏览器中看到它。如果您需要在您的应用程序之外使用文本文件,则如何操作会因平台而异,您将需要使用依赖项服务来获取正确的文件路径。

但是,您可以验证是否已保存并可以读取文件,如下所示:

string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp.txt");
File.WriteAllText(fileName, "Hello World");
Run Code Online (Sandbox Code Playgroud)

以上是您帖子中的代码。如果您没有遇到异常,那么它很可能有效。验证:

var text = File.ReadAllText(filename);
if (text == "Hello World")
    Console.WriteLine("File contents verified and correct");
else
    Console.WriteLine("File contents do not match saved string");
Run Code Online (Sandbox Code Playgroud)