我已经使用 PCL 存储包为我的应用程序创建了一个文件夹。我提到了 this .这是我的代码示例:
public ListPage()
{
testFile();
Content = new StackLayout
{
Children = {
new Label { Text = "Hello ContentPage" }
}
};
}
async public void testFile()
{
// get hold of the file system
IFolder rootFolder = FileSystem.Current.LocalStorage;
// create a folder, if one does not exist already
IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder", CreationCollisionOption.OpenIfExists);
// create a file, overwriting any existing file
IFile file = await folder.CreateFileAsync("MyFile.txt", CreationCollisionOption.ReplaceExisting);
// populate the file with some text
await file.WriteAllTextAsync("Sample Text...");
}
文件文件夹正在 sdcard/android/data/目录下创建,但它不会在文件下创建“MySubFolder”文件夹。
我已经为我的 android 项目设置了 WRITE_EXTERNAL_STORAGE 和 READ_EXTERNAL_STORAGE。我是否缺少任何其他配置?
最佳答案
遇到过类似的问题(虽然在 iOS 上),我现在可以正常工作了,也许它对你有帮助。问题是正确处理异步调用和其他线程乐趣。
首先,我的用例是我将一些文件资源与应用程序捆绑在一起,在第一次运行时为用户提供,但从那时起在线更新。因此,我获取捆绑资源并将它们复制到适当的文件系统中:
var root = FileSystem.Current.LocalStorage;
// already run at least once, don't overwrite what's there
if (root.CheckExistsAsync(TestFolder).Result == ExistenceCheckResult.FolderExists)
{
_testFolderPath = root.GetFolderAsync(TestFolder).Result;
return;
}
_testFolderPath = await root.CreateFolderAsync(TestFolder, CreationCollisionOption.FailIfExists).ConfigureAwait(false);
foreach (var resource in ResourceList)
{
var resourceContent = ResourceLoader.GetEmbeddedResourceString(_assembly, resource);
var outfile = await _testFolderPath.CreateFileAsync(ResourceToFile(resource), CreationCollisionOption.OpenIfExists);
await outfile.WriteAllTextAsync(resourceContent);
}
注意 .ConfigureAwait(false)。我从优秀的人那里学到了这一点
MSDN Best Practises article on async/await .
之前,我一直在不创建目录或文件的方法(如您的问题)或线程挂起之间来回切换。文章对后者进行了详细的讨论。
ResourceLoader 类来自这里:
ResourceToFile() 方法只是一个帮助程序,可以将 iOS 中的长资源名称转换为短文件名,正如我更喜欢的那样。这里不是 germaine(IOW:这是一个我羞于展示的拼凑;)
我想我一天比一天更了解线程,如果我理解正确,这里的技巧是确保您等待加载和写入文件的异步方法完成,但请确保您在线程池上执行此操作不会与主 UI 线程死锁。
关于c# - PCL 存储包不创建文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35596519/