有没有其他方法可以检查文件是否存在于 Windows 应用商店应用程序中?
try
{
var file = await ApplicationData.Current.LocalFolder.GetFileAsync("Test.xml");
//no exception means file exists
}
catch (FileNotFoundException ex)
{
//find out through exception
}
有没有其他方法可以检查文件是否存在于 Windows 应用商店应用程序中?
try
{
var file = await ApplicationData.Current.LocalFolder.GetFileAsync("Test.xml");
//no exception means file exists
}
catch (FileNotFoundException ex)
{
//find out through exception
}
根据这篇文章中接受的答案,目前没有其他办法。但是,File IO 团队正在考虑更改 api 以使其返回 null 而不是引发异常。
引用链接帖子:
目前检查文件是否存在的唯一方法是捕获 FileNotFoundException。正如已经指出的那样,有一个明确的检查并且打开是一个竞争条件,因此我不希望添加任何文件存在 API。我相信 File IO 团队(我不在那个团队,所以我不确定,但这是我听说的)正在考虑让这个 API 返回 null 而不是在文件不存在时抛出。
这可能已经过时了,但看起来他们已经改变了他们希望你处理这个问题的方式。
您应该尝试创建该文件,然后如果该文件已存在则返回。这是关于它的文档。我正在更新这个,因为这是我在谷歌搜索这个问题的第一个结果。
所以,就我而言,我想打开一个文件,或者如果它不存在则创建它。我所做的是创建一个文件,如果它已经存在则打开它。像这样:
save = await dir.CreateFileAsync(myFile, CreationCollisionOption.OpenIfExists);
我偶然发现了 Shashank Yerramilli 的这篇博客文章,它提供了一个更好的答案。
我已经在 windows phone 8 上测试过了,它可以工作。不过还没有在windows store上测试过
我在这里复制答案
对于 Windows RT 应用程序:
public async Task<bool> isFilePresent(string fileName)
{
var item = await ApplicationData.Current.LocalFolder.TryGetItemAsync(fileName);
return item != null;
}
对于 Windows 电话 8
public bool IsFilePresent(string fileName)
{
return System.IO.File.Exists(string.Format(@"{0}\{1}", ApplicationData.Current.LocalFolder.Path, fileName);
}
您可以像这样使用旧的 Win32 调用来测试目录是否存在:
GetFileAttributesExW(path, GetFileExInfoStandard, &info);
return (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? false: true;
它适用于桌面和 Metro 应用程序:http: //msdn.microsoft.com/en-us/library/windows/desktop/aa364946%28v=vs.85%29.aspx
微软在 Windows 8.1 中的 StorageFile 中增加了一个新功能,允许用户工程师确定文件是否可以访问:IsAvailable
另一种检查方法是获取本地文件夹中的文件
var collection = ApplicationData.Current.LocalFolder.GetFilesAsync()
使用此方法,然后遍历集合中的所有元素并检查其可用性。
我尝试使用旧技巧编写自己的:
总而言之——你最好坚持使用异常处理方法。
8.1有这样的东西,我试过了。
var folder = ApplicationData.Current.LocalFolder;
var file = await folder.TryGetItemAsync("mytext.txt") as IStorageFile;
if (file == null)
{
//do what you want
}
else
{
//do what you want
}
Dim myPath As StorageFolder
If (From i In Await KnownFolders.MusicLibrary.GetFoldersAsync() Where i.Name = "PodBong").Count = 1 Then
myPath = Await KnownFolders.MusicLibrary.GetFolderAsync("PodBong")
Else
myPath = Await KnownFolders.MusicLibrary.CreateFolderAsync("PodBong")
End If
TryGetItemAsync的文档说:“此示例显示了如何检查文件是否存在。” 看来这个 API 是为了达到这个目的。