Đường dẫn động trong C#

Đường dẫn động trong C# giúp phần mềm lấy file dữ liệu mà không bị phụ thuộc bởi đường dẫn

  1. Lấy đường dẫn thư mục hiện tại (động theo vị trí chạy)
  2. Lấy đường dẫn thư mục chứa file .exe đang chạy
  3. Lấy đường dẫn động trong ASP.NET (ứng dụng web)

Trong C#, "đường dẫn động" có thể hiểu theo nhiều cách tùy theo ngữ cảnh. Dưới đây là một số tình huống phổ biến và cách lấy đường dẫn động tương ứng:

1. Lấy đường dẫn thư mục hiện tại (động theo vị trí chạy)

string currentDirectory = Directory.GetCurrentDirectory();

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string currentDir = Directory.GetCurrentDirectory();
        Console.WriteLine("Thư mục hiện tại: " + currentDir);
    }
}

2. Lấy đường dẫn thư mục chứa file .exe đang chạy

string exePath = AppDomain.CurrentDomain.BaseDirectory;

    Thường dùng trong WinForms, Console hoặc WPF để lấy đường dẫn tương đối tới thư mục chứa file thực thi.

using System;

class Program
{
    static void Main()
    {
        string exePath = AppDomain.CurrentDomain.BaseDirectory;
        Console.WriteLine("Thư mục chứa file .exe: " + exePath);
    }
}

3. Lấy đường dẫn động trong ASP.NET (ứng dụng web)

a. Lấy đường dẫn vật lý (tuyệt đối trên ổ đĩa)

string physicalPath = Server.MapPath("~/uploads");

// Trong một Controller hoặc WebForm (.aspx.cs)
string physicalPath = Server.MapPath("~/uploads");
Response.Write("Đường dẫn vật lý: " + physicalPath);

b. Lấy đường dẫn URL của trang hiện tại

string url = HttpContext.Current.Request.Url.ToString();

string fullUrl = HttpContext.Current.Request.Url.ToString();
// Ví dụ: http://localhost:1234/Home/Index

Tìm kiếm:

Đường dẫn động trong C# giúp phần mềm lấy file dữ liệu mà không bị phụ thuộc bởi đường dẫn