0

Error: Use of unassigned local variable 'Datafiles'

I know this question is asked several times, but I don't see anything that suits my requirement. please help!

From the following code to check if files exists, I'm getting the following error, any suggestion on how to fix it, I've already included system.IO on top in namespaces

    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;
    }

Thanks fr your help in advance.

RAP
  • 83
  • 2
  • 10
  • You're not assigning a value to `DataFiles`, but you're trying to use its `Length` field. It's not clear what you expect `DataFiles.Length` to test, but perhaps you forgot to assign a value to it? Maybe using `Directory.GetFiles`? (As an aside, I'd recommend that you follow C# conventions, starting local variables with a lower case variable.) – Jon Skeet May 17 '21 at 21:32
  • You did not initialize `DataFiles`, the compiler forbids you to "get" a value from it until you do. This rule applies to all (local) variables declared in methods. – Peter B May 17 '21 at 21:32
  • There are so many duplicates that explain why do you get this error that I really find difficult to believe that you don't get _anything that suits my requirement_ – Steve May 17 '21 at 21:36
  • Thanks Jon, I changed it to string dataFilesLocation; string[] dataFiles; Could you please tell me how to initialize? This is a code I got to check if files exists in a folder, if yes flag true else exit. – RAP May 17 '21 at 21:36

2 Answers2

3

You need to assign both variables before you use them, and a best-practice in C# is to assign variables on the line you declare them, if you can.

So it should look something like:

  string dataFilesLocation = Dts.Variables["User::FolderPath"].Value.ToString();
  string[] dataFiles = System.IO.Directory.GetFiles(dataFilesLocation);
David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67
1

You never assign anything to DataFiles. Try initializing it with an array size and populating those indexes, or assigning an array to it. 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;
}
StarshipladDev
  • 1,166
  • 4
  • 17