[C# 윈폼] C# 프로그램 경로(Path) 가져오기

안녕하세요.

 

오늘은 C# 문법에서 프로그램 시작 경로(Path)를 가져오는 여러가지 방법에 대해서 알려 드리려고 합니다.

 

C# 프로젝트를 진행하다 보면, 프로그램 시작 경로를 가져오거나 필요로 하는 경우가 종종 있는데요.

 

이럴 때 매우 유용하게 사용하실 수 있는 문법이라고 생각합니다.

 

그럼 바로 예제를 통해서 프로그램 경로를 어떻게 가져 오는지 예제 코드를 통해서 보여 드리도록 하겠습니다.

 

먼저 아래와 같이 윈폼 프로젝트를 하나 생성해 주시고, TextBox 컨트롤 하나를 배치해 주시기 바랍니다.

 

빈 윈폼 프로젝트 생성 및 TextBox 컨트롤 배치

위와 같이 label,  TextBox 컨트롤을 배치해 주시기 바랍니다.

 

그럼 이제 위의 비하인드 소스코드를 작성해 보도록 하겠습니다.

 

예제 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace PathTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
 
            this.Load += FormLoad_Event;
        }
 
        private void FormLoad_Event(object sender, EventArgs e)
        {
            GetCurrentPath();
        }
 
        private void GetCurrentPath()
        {
            uiTb_path1.Text = $"현재 경로 : {Environment.CurrentDirectory}";
            uiTb_path2.Text = $"현재 경로 : {AppDomain.CurrentDomain.BaseDirectory}";
            uiTb_path3.Text = $"현재 경로 : {Application.ExecutablePath}";
 
            string folderPath = string.Empty;
            folderPath = Application.ExecutablePath;
            int index = folderPath.LastIndexOf('\\');
 
            folderPath = folderPath.Remove(index, folderPath.Length - index);
 
            uiTb_path4.Text = $"현재 경로 : {folderPath.ToString()}";
        }
    }
}
 
cs

 

실행 결과

위와 같이 여러가지 방법으로 현재 경로를 가져오는 방법에 대해서 알아 보았습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY