Xamarin Forms:如何将数据写入便携式文件夹中添加的文件?



我在项目的便携文件夹中添加了一个文件,并将其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.IO. streamwriter ..Stream Stream, System. text . encoding, encoding, System。Int32 bufferSize, System。[0x00035] in/Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/Common/src/CoreLib/System/IO/StreamWriter.cs:115在System.IO. streamwriter ..Stream Stream) [0x00000] in/Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/Common/src/CoreLib/System/IO/StreamWriter.cs:88at (wrapper remoting-invoke-with-check) System.IO.StreamWriter. tor(System.IO.Stream)

我需要将数据写入保存在项目便携文件夹中的文件。由于

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());
}

相关内容

  • 没有找到相关文章

最新更新