问题 UWP检查文件是否存在
我目前正在开发Windows 10 UWP应用程序。
应用程序需要检查某个PDF文件是否存在,称为“01-introduction”,如果是,则打开它。
如果文件不存在,我已经有了代码。
以下代码是我目前拥有的:
try
{
var test = await DownloadsFolder.CreateFileAsync("01-Introduction.pdf", CreationCollisionOption.FailIfExists);
}
catch
{
}
此代码无法正常工作,因为检查文件是否存在此处,我尝试创建该文件。但是,如果该文件尚不存在,则将创建一个空文件。如果文件不存在,我不想创建任何内容,只要打开PDF即可。
如果可能的话,我想查看名为“我的手册”的下载文件夹中的文件夹。
任何帮助将不胜感激。
11765
2018-05-09 15:18
起源
答案:
public async Task<bool> isFilePresent(string fileName)
{
var item = await ApplicationData.Current.LocalFolder.TryGetItemAsync(fileName);
return item != null;
}
但不支持Win8 / WP8.1
https://blogs.msdn.microsoft.com/shashankyerramilli/2014/02/17/check-if-a-file-exists-in-windows-phone-8-and-winrt-without-exception/
8
2018-05-11 03:16
有两种方法
1)你可以使用 StorageFolder.GetFileAsync()
因为Windows 8.1和WP 8.1设备也支持此功能。
try
{
StorageFile file = await DownloadsFolder.GetFileAsync("01-Introduction.pdf");
}
catch
{
Debug.WriteLine("File does not exits");
}
2)或者你可以使用 FileInfo.Exists
仅支持Windows 10 UWP。
FileInfo fInfo = new FileInfo("01-Introduction.pdf");
if (!fInfo.Exists)
{
Debug.WriteLine("File does not exits");
}
5
2018-05-09 21:00
System.IO.File.Exists也是UWP方式。我现在在Windows IOT中测试。它只是工作。
2
2017-11-30 13:25
您可以使用System.IO.File。
例:
// If file located in local folder. You can do the same for other locations.
string rootPath = ApplicationData.Current.LocalFolder.Path;
string filePath = Path.Combine(rootPath, "fileName.pdf");
if (System.IO.File.Exists(filePath))
{
// File exists
}
else
{
// File doesn't exist
}
0
2017-09-17 18:00
我正在做一个Win10 IoT核心UWP应用程序,我必须检查文件长度而不是“存在”因为 CreateFileAsync()
已经立即创建一个空文件存根。但我之前需要调用以确定文件所在的整个路径。
所以就是:
var destinationFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("MyFile.wow", ...);
if (new FileInfo(destinationFile.Path).Length > 0)
return destinationFile.Path;
0
2017-08-02 20:09
通过这种方式 System.IO.File.Exists(filePath)
我无法测试 DocumentLibrary
因为 KnownFolders.DocumentsLibrary.Path
返回空字符串
下一个解决方案非常慢 await DownloadsFolder.GetFileAsync("01-Introduction.pdf")
恕我直言,最好的方法是从文件夹中收集所有文件并检查文件名是否存在。
List<StorageFile> storageFileList = new List<StorageFile>();
storageFileList.AddRange(await KnownFolders.DocumentsLibrary.GetFilesAsync(CommonFileQuery.OrderByName));
bool fileExist = storageFileList.Any(x => x.DisplayName == "01-Introduction.pdf");
0
2017-12-02 15:31
在这种情况下,您可以使用FileInfo类。它有一个名为FileInfo.Exists()的方法,它返回一个bool结果
https://msdn.microsoft.com/en-us/library/system.io.fileinfo.exists(v=vs.110).aspx
编辑:
如果要检查文件是否存在,则需要创建一个StorageFile对象并调用其中一个GetFile ....方法。如:
StorageFile file = new StorageFile();
file.GetFileFromPathAsync("Insert path")
if(file == null)
{
/// File doesn't exist
}
我快速查看下载文件夹路径但没有快乐,但GetFile方法应该为您提供所需的答案
-1
2018-05-09 15:28
在Window 10上,对我来说,这是最“优雅”的方式:
private static bool IsFileExistent(StorageFile file)
{
return File.Exists(Path.Combine(file.Path));
}
或者,如果您愿意并将广泛使用它作为扩展:
static class Extensions
{
public static bool Exists(this StorageFile file)
{
return File.Exists(Path.Combine(file.Path));
}
}
-1
2018-03-29 18:28