C#编译报错Use of unassigned local variable

C# compile error Use of unassigned local variable

错误:使用了未分配的局部变量 'Datafiles'

我知道这个问题被问过好几次了,但我没有看到任何符合我要求的问题。请帮助!

从以下代码检查文件是否存在,我收到以下错误,关于如何修复它的任何建议,我已经在名称空间

的顶部包含了 system.IO
    public void Main()
    {
        // TODO: Add your code here

        string DataFilesLocation;
        string[] DataFiles ;

        DataFilesLocation = Dts.Variables["User::FolderPath"].Value.ToString();
        if (DataFiles.Length > 0)
        {
            Dts.Variables["User::Flag"].Value = true;
        }

        Dts.TaskResult = (int)ScriptResults.Success;
    }

在此先感谢您的帮助。

您永远不会为 DataFiles 分配任何内容。 尝试使用数组大小​​对其进行初始化并填充这些索引,或为其分配一个数组。 E.G

public void Main()
{
    string DataFilesLocation;
    // initializes your variable, removing the error you are getting
    string[] DataFiles = new string[5];
    //populates the array with file names 
    for(int i=0 ; i< 5 ; i++){
        DataFiles[i]="FilePrefix"+i+".png";
    }

    DataFilesLocation = Dts.Variables["User::FolderPath"].Value.ToString();
    if (DataFiles.Length > 0)
    {
        Dts.Variables["User::Flag"].Value = true;
    }

    Dts.TaskResult = (int)ScriptResults.Success;
}

您需要在使用这两个变量之前对其进行赋值,C# 中的最佳做法是尽可能在声明它们的行上赋值。

所以它应该看起来像:

  string dataFilesLocation = Dts.Variables["User::FolderPath"].Value.ToString();
  string[] dataFiles = System.IO.Directory.GetFiles(dataFilesLocation);