【问题标题】:Xamarin Forms: How to write data to a file added in the portable folder?Xamarin Forms:如何将数据写入可移植文件夹中添加的文件?
【发布时间】:2021-03-03 23:30:11
【问题描述】:

我在项目的可移植文件夹中添加了一个文件,并将其Build Action 设置为Embedded Resource。我正在尝试使用以下代码将数据写入该文件:

string data ="123";
string fileName = "Files.STOCK.TXT";
var assembly = typeof(HomePage).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{fileName}");
using (var streamWriter = new System.IO.StreamWriter(stream))
{
    streamWriter.WriteLine(data);
}

运行时出现以下异常:

System.ArgumentException:流不可写。 在 System.IO.StreamWriter..ctor (System.IO.Stream 流,System.Text.Encoding 编码,System.Int32 bufferSize,System.Boolean leaveOpen)[0x00035] 在 /Users/builder/jenkins/workspace/archive-mono /2020-02/android/release/external/corefx/src/Common/src/CoreLib/System/IO/StreamWriter.cs:115 在 System.IO.StreamWriter..ctor (System.IO.Stream 流) [0x00000] 在 /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/Common/ src/CoreLib/System/IO/StreamWriter.cs:88 在 (wrapper remoting-invoke-with-check) System.IO.StreamWriter..ctor(System.IO.Stream)

我需要将数据写入项目可移植文件夹中保存的文件。谢谢

【问题讨论】:

    标签: file xamarin.forms


    【解决方案1】:

    来自 GetManifestResourceStream 的流不可写。流的文件在构建时嵌入到程序集中,无法更改。您需要先将文件写入磁盘,然后才能写入。

    string resource = "Files.STOCK.TXT";
    using (Stream stream = assembly.GetManifestResourceStream(resource))
    using (var fs = new FileStream(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal)), FileMode.Create, FileAccess.Write))
    using (var stream = new MemoryStream())
    using (var writer = new StreamWriter(fs))
    {
        Stream.Stream.CopyTo(stream);
        writer.Write(stream.ToArray());
    }
    

    【讨论】:

    • 我需要将数据写入到便携式文件夹中保存的文件中。在我们传递数据的代码上?
    • 只需要设置你想要的fs就可以了
    • 所以不可以向可移植项目中添加的文件写入数据?
    • 最好写到外部文件夹。
    • 如果对你有帮助别忘了接受我的回答:)
    猜你喜欢
    • 1970-01-01
    • 2011-05-02
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2020-05-23
    • 1970-01-01
    相关资源
    最近更新 更多