报错,不明白为什么

Getting an error and don't understand why

我已经无计可施了。我正在编写一些程序代码,从 excel 工作表中获取文件名。然后代码应该从基目录开始递归地找到每个文件,然后将每个文件复制到一个位置。

我的代码迭代一次,然后在第二次迭代时产生一个错误,指出我在第 47 行的 'justPath' 变量不能为空。

我已经发布了下面的代码。非常感谢任何帮助。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;

namespace ExcelManip
{
    class Program
    {
        static void Main(string[] args)
        {        
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Users\employee1234\Desktop\Reload_837_X12_Raw.xlsx", 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", true, false, 0, true, 1, 0);
            Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[4];
            Excel.Range xlRange = xlWorksheet.UsedRange;
            int rowCount = xlRange.Rows.Count;
            int colCount = xlRange.Columns.Count;
            int actualRows = rowCount - 1;
            int y = 0;
            int z = 1;         
            string targetPath = @"C:\Users\employee1234\Desktop\dropfiles";
            for (int count = 11; count <= rowCount; count++){
                var currentIndex = count;
                var yy = y;
                Console.WriteLine(yy);
                string temp = (string)(xlRange.Cells[currentIndex, 2] as Excel.Range).Value2; 
                string[] filePaths = Directory.GetFiles(@"\fileshare01\Data\subfolder1\subfolder2\", temp, SearchOption.AllDirectories);
                Array.Resize(ref filePaths, filePaths.Length + 1);
                string filePath = filePaths[yy];
                string justPath = Path.GetDirectoryName(filePath);     
                string sourceFile = System.IO.Path.Combine(justPath, temp);                
                string destFile = System.IO.Path.Combine(targetPath, temp);
                Console.WriteLine("File Path " + z+ " of "+ actualRows +" : "+ filePath + "\n");
                System.IO.File.Copy(sourceFile, destFile, true);
                y++;
                z++;
                               }
            xlWorkbook.Save();
            xlWorkbook.Close(0);
            xlApp.Quit();
            GC.Collect();


      }
    }
}

Path.GetDirectoryName 方法来自 .NET documentation:

Return Value Type: System.String Directory information for path, or null if path denotes a root directory or is null. Returns String.Empty if path does not contain directory information.

进一步评论:

In most cases, the string returned by this method consists of all characters in the path up to but not including the last DirectorySeparatorChar or AltDirectorySeparatorChar. If the path consists of a root directory, such as "c:\", null is returned. Note that this method does not support paths using "file:". Because the returned path does not include the DirectorySeparatorChar or AltDirectorySeparatorChar, passing the returned path back into the GetDirectoryName method will result in the truncation of one folder level per subsequent call on the result string. For example, passing the path "C:\Directory\SubDirectory\test.txt" into the GetDirectoryName method will return "C:\Directory\SubDirectory". Passing that string, "C:\Directory\SubDirectory", into GetDirectoryName will result in "C:\Directory".

Array.Resize(参考文件路径,filePaths.Length + 1);此行将空字符串附加到 filePaths 数组。如果 yy 计数器走那么远就是这样..

问题是您有一个变量 y,您每次在循环中递增该变量。我假设您认为此行附加到数组:

string[] filePaths = Directory.GetFiles(@"\fileshare01\Data\subfolder1\subfolder2\", temp, SearchOption.AllDirectories);

没有。它创建一个新数组。因此,假设只有一个文件具有您想要的名称,下一次循环 y == 1 并且您指向返回结果之外的空值,指向您附加到数组的空值。

如果要存储文件的实际路径,则需要在循环外定义一个变量并添加到该变量中。例如List<string>。但由于您只是复制,因此不需要这样做。

此外,为什么要复制像 yycurrentIndex 这样的变量,如果它们只是指向根本没有修改的变量 ycount

即使您 知道 总是有一个具有该名称的文件,但实际测试它和 when[=33] 仍然没有什么坏处=] 正好有文件不存在,可以输出错误。

你的循环应该更像:

var paths = new List<string>();
for (int count = 11; count <= rowCount; count++){
    string temp = (string)(xlRange.Cells[count, 2] as Excel.Range).Value2; 
    string[] filePaths = Directory.GetFiles(@"\fileshare01\Data\subfolder1\subfolder2\", temp, SearchOption.AllDirectories);
    if ((filePaths == null) || (filePaths.Length == 0))
    {
      Console.WriteLine("Didn't find file: " + temp);
      continue; // Or break, or exit, or...
    }
    string filePath = filePaths[0];
    // If the temp is a single filename (no globs), you don't even need the next two lines
    string justPath = Path.GetDirectoryName(filePath);     
    string sourceFile = System.IO.Path.Combine(justPath, temp);                
    string destFile = System.IO.Path.Combine(targetPath, temp);
    Console.WriteLine("File Path " + z+ " of "+ actualRows +" : "+ filePath + "\n");
    System.IO.File.Copy(sourceFile, destFile, true);
    paths.Add(sourceFile); // or destFile, or what you want to store
    z++;
}