C# 获取当程序的位置
时间: 2023-10-19 19:29:11 浏览: 58
在 C# 中,可以使用 `System.Reflection.Assembly` 类的 `GetEntryAssembly` 方法获取当前程序集的引用,然后可以调用其 `Location` 属性获取当前程序的位置(即可执行文件的路径)。
示例代码:
```csharp
using System.Reflection;
string exePath = Assembly.GetEntryAssembly().Location;
```
注意,该方法返回的是可执行文件的绝对路径,包括文件名。如果需要获取可执行文件所在的目录,可以使用 `Path.GetDirectoryName` 方法获取。
示例代码:
```csharp
using System.Reflection;
using System.IO;
string exeDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
```
这段代码会返回当前程序的目录,例如:`C:\Program Files (x86)\MyApp`。注意,该目录不包括可执行文件的名称。
相关问题
c# 获取当前程序占用资源
在C#中,可以使用System.Diagnostics.Process类获取当前程序占用的资源,例如CPU和内存等。以下是示例代码:
```csharp
using System.Diagnostics;
Process currentProcess = Process.GetCurrentProcess();
// 获取当前程序占用的CPU时间
TimeSpan cpuTime = currentProcess.TotalProcessorTime;
// 获取当前程序占用的内存大小
long memorySize = currentProcess.WorkingSet64;
Console.WriteLine("CPU时间: {0}", cpuTime);
Console.WriteLine("内存大小: {0} bytes", memorySize);
```
在上面的代码中,首先使用Process.GetCurrentProcess()方法获取当前进程的Process对象。然后通过该对象的TotalProcessorTime属性获取当前程序占用的CPU时间,通过WorkingSet64属性获取当前程序占用的内存大小。
注意:在使用Process类获取当前程序占用资源时,需要有足够的权限,否则可能会抛出SecurityException异常。
c# 获取当前程序windows日志
您可以使用 System.Diagnostics.EventLog 类来读取 Windows 日志。以下是一个简单的 C# 代码示例,演示了如何读取当前程序的日志:
```csharp
using System.Diagnostics;
// 获取当前程序的 EventLog
EventLog appLog = new EventLog("Application", ".", Process.GetCurrentProcess().ProcessName);
// 读取最近的 100 条日志
foreach (EventLogEntry entry in appLog.Entries.Cast<EventLogEntry>().Reverse().Take(100))
{
Console.WriteLine("{0}: {1}", entry.TimeGenerated, entry.Message);
}
```
这段代码会输出最近的 100 条应用程序日志。您可以根据需要修改日志的来源、数量、筛选条件等。另外,请确保您的程序有足够的权限来读取 Windows 日志。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)