首页 > 解决方案 > 将文件路径值传递给 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'

标签: c#openxmlfilepicker

解决方案


这个问题的简短答案在这里:

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 窗体应用程序,以完全避免此问题。


推荐阅读