获取程序运行路径的几种方法

本文介绍了几种在Windows环境下获取路径的方法,包括获取当前模块文件名(GetModuleFileName)、获取当前工作目录(_getcwd)以及从命令行参数中提取路径(GetCommandLine)等。通过这些方法可以方便地在应用程序中使用文件和目录。

 

.GetModuleFileName()

 char path[255];
 GetModuleFileName(AfxGetInstanceHandle(),   path,   MAX_PATH-1);

 

. _getcwd

#include <direct.h>

char path[255];
 _getcwd(path,255);

.GetCommandLine

#include "Shlwapi.h"
 LPSTR path = ::GetCommandLine(); 

PathRemoveArgs(path);   //Path.RemoveArgs();
 PathUnquoteSpaces(path);  //Path.UnquoteSpaces();
 PathRemoveFileSpec(path);  //Path.RemoveFileSpec();
 PathAppend(path,"test.ini");

在Visual Studio Code中使用C#获取程序运行路径,可借助`System.IO`和`System.Reflection`命名空间里的类和方法。下面给出几种常见的获取程序运行路径的方式。 ### 使用`System.IO.Directory.GetCurrentDirectory`方法方法能够返回当前工作目录的路径。示例代码如下: ```csharp using System; using System.IO; class Program { static void Main() { string currentDirectory = Directory.GetCurrentDirectory(); Console.WriteLine("当前工作目录: " + currentDirectory); } } ``` ### 使用`System.Reflection.Assembly.GetExecutingAssembly`方法方法获取当前执行的程序集,然后借助`Location`属性得到程序集的路径。示例代码如下: ```csharp using System; using System.Reflection; class Program { static void Main() { string assemblyLocation = Assembly.GetExecutingAssembly().Location; string directory = System.IO.Path.GetDirectoryName(assemblyLocation); Console.WriteLine("程序集所在目录: " + directory); } } ``` ### 使用`System.AppContext.BaseDirectory`属性 这个属性会返回包含应用程序基目录的字符串,此目录一般是程序运行时的根目录。示例代码如下: ```csharp using System; class Program { static void Main() { string baseDirectory = AppContext.BaseDirectory; Console.WriteLine("应用程序基目录: " + baseDirectory); } } ``` 要在Visual Studio Code里运行这些代码,需确保已经配置好C#的运行环境。可以按照以下步骤操作: 1. 下载并安装.NET SDK,从而为C#提供运行时环境。 2. 在Visual Studio Code中安装C#扩展,以此来支持C#代码的编写与调试。 3. 创建一个C#项目,编写上述代码,然后运行程序即可看到输出结果。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值