简体   繁体   English

在 C# 中设置当前目录

[英]Set current Directory in C#

I'm trying to change the Directory in my C# code so I can run a batch file.我正在尝试更改 C# 代码中的目录,以便运行批处理文件。

For example:例如:

D:\Program Files\Common Files\asd.bat

However when I use Directory.SetCurrentDirectory(@"D:\Program Files\Common Files\asd.bat");但是,当我使用Directory.SetCurrentDirectory(@"D:\Program Files\Common Files\asd.bat"); it gives me two errors.它给了我两个错误。

  1. Invalid token '(' in class, struct, or interface member declaration Error class 中的无效标记 '('、结构或接口成员声明错误
  2. 'System.IO.Directory.SetCurrentDirectory(string)' is a 'method' but is used like a 'type' 'System.IO.Directory.SetCurrentDirectory(string)' 是一种“方法”,但像“类型”一样使用

Could anyone help me please.谁能帮帮我。 I'm still new to C#.我还是 C# 的新手。

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).出现这样的错误意味着未正确设置对库的引用(缺少 using 或未设置对 .NET class 或 NUGET package 的依赖项)。 In this case, you can either declare using System.IO;在这种情况下,您可以声明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.当您调用System.IO.Directory.SetCurrentDirectory(path)时,它必须是没有文件名的路径。 You passed the full path including the file name asd.bat .您传递了包括文件名asd.bat在内的完整路径。

To get the path, use System.IO.Path.GetDirectoryName , like:要获取路径,请使用System.IO.Path.GetDirectoryName ,例如:

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;注意:当然,你可以通过声明using System.IO; on the top - I didn't do it here, so it is clear where the method comes from.在顶部-我没有在这里做,所以很清楚方法的来源。

The error must be somewhere else.错误必须在其他地方。 Maybe you did put your code directly in the class and not inside a member?也许你没有把你的代码直接放在 class 而不是在成员里面?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM