using System;
using System.IO;
class Program
{
static void Main()
{
// 获取当前执行程序的目录
string currentDirectory = Directory.GetCurrentDirectory();
Console.WriteLine("当前目录: " + currentDirectory);
// 定义一个相对路径
string relativePath = @"..\..\example.txt";
// 将相对路径转换为绝对路径
string absolutePath = Path.GetFullPath(relativePath);
Console.WriteLine("绝对路径: " + absolutePath);
// 检查文件是否存在
if (File.Exists(absolutePath))
{
Console.WriteLine("文件存在");
}
else
{
Console.WriteLine("文件不存在");
}
}
}
Directory.GetCurrentDirectory()
方法获取当前执行程序所在的目录。relativePath
是一个相对路径,表示从当前目录向上两级目录找到 example.txt
文件。Path.GetFullPath(relativePath)
方法将相对路径转换为绝对路径。File.Exists(absolutePath)
方法检查指定路径的文件是否存在。通过这段代码,你可以理解如何在 C# 中处理相对路径并将其转换为绝对路径进行文件操作。
上一篇:c#网页开发
下一篇:c# 写文本文件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站