'Set current Directory in C#
I'm trying to change the Directory in my C# code so I can run a batch file.
For example:
D:\Program Files\Common Files\asd.bat
However when I use Directory.SetCurrentDirectory(@"D:\Program Files\Common Files\asd.bat"); it gives me two errors.
- Invalid token '(' in class, struct, or interface member declaration Error
- 'System.IO.Directory.SetCurrentDirectory(string)' is a 'method' but is used like a 'type'
Could anyone help me please. I'm still new to C#.
Solution 1:[1]
The error must be somewhere else. Maybe you did put your code directly in the class and not inside a member?
Solution 2:[2]
Old question, but the accepted answer isn't correct.
Getting errors like this means the reference to a library is not correctly set up (either a using is missing or a dependency to a .NET class or NUGET package is not set). In this case, you can either declare using System.IO; on the top or reference the methods by fully qualifying the namespace (like I am doing it below).
Regarding the method you want to use, there is additionally another issue:
When you call System.IO.Directory.SetCurrentDirectory(path), then it must be a path without filename. You passed the full path including the file name asd.bat.
To get the path, use System.IO.Path.GetDirectoryName, like:
var pathWithFileName = @"D:\Program Files\Common Files\asd.bat";
var pathOnly = System.IO.Path.GetDirectoryName(pathWithFileName);
System.IO.Directory.SetCurrentDirectory(pathOnly);
If you want to check if the path exists beforehand, use
if (System.IO.Directory.Exists(pathOnly)) System.IO.Directory.SetCurrentDirectory(pathOnly);
Note: Of course, you can abbreviate the code above by declaring using System.IO; on the top - I didn't do it here, so it is clear where the method comes from.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | balinta |
| Solution 2 |
