c# - 将文件路径值传递给 OpenXML GetCellValue() 时的 System.IO.FileNotFound
问题描述
当我将 OpenFilePicker() 方法中的值传递回按钮单击方法时,我可以使用调试字符串并确保该值不为空。
但是,当我将它传递给 GetCellValue() 方法时,会引发“FileNotFound”异常。此处使用调试语句还表明该值不为空,并返回“C:\Test.xlsx”的有效文件路径。
尝试将所有文件权限更改为 RWX,尝试不同的文件夹位置。所有权限和文件夹似乎都有相同的问题。
public async void FileSelectButton_ClickAsync(object sender, RoutedEventArgs e)
{
string filePath = await openFilePicker();
//Debug.WriteLine("result:: " + filePath);
GetCellValue(filePath, "Sheet1", "A1");
}
public async Task<string> openFilePicker()
{
var archerReportPicker = new
Windows.Storage.Pickers.FileOpenPicker();
archerReportPicker.ViewMode =
Windows.Storage.Pickers.PickerViewMode.Thumbnail;
archerReportPicker.SuggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.Downloads;
archerReportPicker.FileTypeFilter.Add(".xlsx");
archerReportPicker.FileTypeFilter.Add(".xls"); // Default extensions
Windows.Storage.StorageFile archerReport = await archerReportPicker.PickSingleFileAsync(); //Get file
if (archerReport != null)
{
// Application now has read/write access to the picked file
this.fileTextBox.Text = archerReport.Name; // Load it up and throw the data in the textbox.
var filePath = archerReport.Path;
return filePath;
}
else
{
this.fileTextBox.Text = "";
return null;
}
}
public static string GetCellValue(string fileName, string sheetName, string addressName)
{
string value = null;
// Open the spreadsheet document for read-only access.
using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false)) //Line where exception is thrown
{...}
引发 System.IO.FileNotFound 异常,而不是打开有效的文件路径。
当使用定义 filePath 或 fileName 时也会出现此问题const string '@c:\test.xlsx'
解决方案
这个问题的简短答案在这里:
https://blogs.msdn.microsoft.com/wsdevsol/2012/12/04/skip-the-path-stick-to-the-storagefile/
它的要点是在 UWP 中,存储选择器返回一个非文件系统绑定的 Windows.Storage 对象。您可以从对象中收集文件系统路径,但由于您正在对辅助对象执行操作,因此用户授予第一个对象的权限这一事实不适用于第二个对象,从而导致尝试打开时出现访问被拒绝的情况该文件 - 即使 NTFS 权限允许“所有人”访问。
这可以通过使用 SystemInternals 的 Process Monitor 监控应用程序来确认。
如果我发现此问题的解决方法,我将更新此答案,但我可能会从 UWP 移回 Windows 窗体应用程序,以完全避免此问题。
推荐阅读
- mysql - 在表中插入日期
- python - 如何将文件导入 Tkinter 并运行脚本?
- angular - 将 async/await 与表单组一起使用
- javascript - 创建一个计算 x 的 P 次方的函数(x 和 P 都是整数)
- android-studio - 如何判断当前是否正在使用 flutter_blue 的设备上执行特征读取?
- python - 在 m2m 文件中添加验证错误 - Odoo 10
- sql - 使用宏将值传递给查询时,当值不存在时是否可以继续查询?
- git - How to obtain which lines changed for each commited file with git
- javascript - 如何获取具有匹配数据属性值的 dom 元素?
- powershell - 如何使用 Powershell 发送 ALT+ENTER?