以 xamarin 形式执行此操作?或者我们应该使用依赖服务吗?
选项1:
当然我们需要使用依赖服务。
在Android项目中
public async Task SaveAndView(string fileName, String contentType, MemoryStream stream)
{
try
{
string root = null;
//Get the root path in android device.
if (Android.OS.Environment.IsExternalStorageEmulated)
{
root = Android.OS.Environment.ExternalStorageDirectory.ToString();
}
else
root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//Create directory and file
Java.IO.File myDir = new Java.IO.File(root + "/meusarquivos");
myDir.Mkdir();
Java.IO.File file = new Java.IO.File(myDir, fileName);
//Remove if the file exists
if (file.Exists()) file.Delete();
//Write the stream into the file
FileOutputStream outs = new FileOutputStream(file);
outs.Write(stream.ToArray());
outs.Flush();
outs.Close();
}
catch (Exception ex)
{
//...
}
}
await DependencyService.Get<ISave>().SaveAndView(xxx.ToString() + ".pdf", "application/pdf", stream);
不要忘记添加以下权限并获得运行时权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in iOS
iOS 对应用程序对文件系统的操作施加了一些限制,以保护应用程序数据的安全,并保护用户免受恶意应用程序的侵害。这些限制是应用程序沙箱的一部分 - 一组限制应用程序访问文件、首选项、网络资源、硬件等的规则。应用程序仅限于在其主目录(安装位置)内读取和写入文件;它无法访问其他应用程序的文件。
你可以检查docs更多细节 。
选项2:
如果您确实想直接在 Forms 中实现它。我们可以使用该插件PCL存储来自努吉特。
跨平台本地文件夹
在 Xamarin.Form 中,PCL存储API 将帮助我们使用下面给出的代码检索所有平台的本地文件夹名称和路径。无需编写任何特定于平台的代码即可访问本地文件夹。
Using PCLStorage;
IFolder folder = FileSystem.Current.LocalStorage;
创建新文件夹
若要在本地文件夹中创建新的子文件夹,请调用 CreateFolderAsync 方法。
string folderName ="xxx" ;
IFolder folder = FileSystem.Current.LocalStorage;
folder = await folder.CreateFolderAsync(folderName, CreationCollisionOption.ReplaceExisting);
创建新文件
若要在本地文件夹中创建新文件,请调用 CreateFileAsync 方法。
string filename=”username.txt”;
IFolder folder = FileSystem.Current.LocalStorage;
IFile file = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
检查文件夹是否已存在
我们可以检查特定文件夹中是否存在现有文件夹,如下所示。
public async static Task<bool> IsFolderExistAsync(this string folderName, IFolder rootFolder = null)
{
// get hold of the file system
IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;
ExistenceCheckResult folderexist = await folder.CheckExistsAsync(folderName);
// already run at least once, don't overwrite what's there
if (folderexist == ExistenceCheckResult.FolderExists)
{
return true;
}
return false;
}
检查文件是否已经存在
我们可以检查特定文件夹中是否存在文件,如下所示。
public async static Task<bool> IsFileExistAsync(this string fileName, IFolder rootFolder = null)
{
// get hold of the file system
IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;
ExistenceCheckResult folderexist = await folder.CheckExistsAsync(fileName);
// already run at least once, don't overwrite what's there
if (folderexist == ExistenceCheckResult.FileExists)
{
return true;
}
return false;
}
写入文件
如果要写入任何扩展文件文档,只需使用 WriteAllTextAsync 方法进行写入即可。
public async static Task<bool> WriteTextAllAsync(this string filename, string content = "", IFolder rootFolder = null)
{
IFile file = await filename.CreateFile(rootFolder);
await file.WriteAllTextAsync(content);
return true;
}
注意:Android项目中还需要添加权限。
Update
File类提供了创建、删除、读取共享项目中文件的相关方法,但只能访问应用程序文件夹。
File.WriteAllText(fileName, text);
string text = File.ReadAllText(fileName);
要在外部存储中创建文件,请尝试使用DependencyService在本机平台上实现该功能。
1.创建接口定义方法
public interface IAccessFile
{
void CreateFile(string FileName);
}
2.在android平台上实现服务
[assembly: Xamarin.Forms.Dependency(typeof(AccessFileImplement))]
namespace XamarinFirebase.Droid
{
public class AccessFileImplement : IAccessFile
{
void CreateFile(string FileName)
{
string text = "xxx";
byte[] data = Encoding.ASCII.GetBytes(text);
string DownloadsPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
string filePath = Path.Combine(DownloadsPath, FileName);
File.WriteAllBytes(filePath, data);
}
}
}
3.消费共享项目中的DependencyService命令
DependencyService.Get<IAccessFile>().CreateFile("myfile.txt");
它不能在 iOS 平台上使用,iOS 对应用程序可以对文件系统执行的操作施加一些限制,以保护应用程序数据的安全。
应用程序仅限于读取和写入其主目录(安装位置)内的文件;它无法访问其他应用程序的文件。
相关教程:
https://learn.microsoft.com/en-us/xamarin/android/platform/files/external-storage?tabs=windows
https://learn.microsoft.com/en-us/xamarin/ios/app-fundamentals/file-system#special-considerations