4.1 C#获取目录的3个方法的区别

C#中常用有如下3个获取目录的方式如下

1.Directory.GetCurrentDirectory():获取当前工作目录,工作目录可能被用户或其他代码修改。尽量少用。(似乎只要在运行中使用另存为或者打开某个文件夹,当前工作目录就修改)

2.Application.StartupPath(): 获取应用程序的启动目录,返回不带末尾的'\'

3.AppDomain.CurrentDomain.BaseDirectory:获取应用程序的启动目录,返回带有'\'

复制代码

结论:

  • 通用场景 :优先使用 AppDomain.CurrentDomain.BaseDirectory(更安全、跨平台兼容)。

  • WinForms 专用 :若需要无末尾反斜杠的路径,可使用 Application.StartupPath,但需注意平台限制。

  • Web 或服务 :必须使用 AppDomain.CurrentDomain.BaseDirectory,避免路径错误

复制代码
【修改当前工作路径的代码例子】:
static void Main()
    {
        // 获取当前工作目录
        string currentDir = Directory.GetCurrentDirectory();
        Console.WriteLine($"当前工作目录: {currentDir}");

        // 尝试修改工作目录
        Directory.SetCurrentDirectory(".."); // 切换到上级目录
        Console.WriteLine($"修改后的工作目录: {Directory.GetCurrentDirectory()}");
    }
相关推荐
o52788318417 小时前
校园一体化管理系统2.1、基于整洁四层架构 + DDD+CQRS 项目目录解读
后端·架构·c#·asp.net·visual studio
农村小镇哥1 天前
C#中的字符串格式化
服务器·开发语言·c#
czhc11400756632 天前
719:StartPoint;Margin;ResourceDictionar;Component.model;lds;
c#
-银雾鸢尾-2 天前
C#中的万物之父——Object类
开发语言·c#
水晶石NSIS专栏2 天前
Geek_Studio - 安卓终端调试工作台
android·c#·apk签名·coloros主题
-银雾鸢尾-2 天前
C#中的继承
开发语言·c#
吴可可1232 天前
C#AutoCAD二次开发打断多段线
c#
-银雾鸢尾-2 天前
里氏替换原则
开发语言·c#·里氏替换原则
-银雾鸢尾-2 天前
C#中的索引器
开发语言·c#