C#/C# 매뉴얼
[C#] 폴더/파일 이동, 복사, 삭제 (.Net)
Hostramus
2022. 9. 13. 13:05
반응형
1. Point
- 폴더 / 파일 삭제하기 (delete)
- 폴더 / 파일 복사 - 붙여넣기 (copy)
- 폴더 / 파일 잘라내기 - 붙여넣기 (move)
반응형
2. 전체 코드
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace manual_file_MoveCopyDelete
{
internal class Program
{
static void Main(string[] args)
{
DirectoryInfo s_path = new DirectoryInfo(@".\test_dir");
DirectoryInfo t_path = new DirectoryInfo(@".\test_dir2");
DirectoryInfo s_path2 = new DirectoryInfo(@".\test_dir3");
DirectoryInfo t_path2 = new DirectoryInfo(@".\test_dir4");
// 폴더 4개 생성
s_path.Create();
t_path.Create();
s_path2.Create();
t_path2.Create();
// 파일 유무 확인
// 'Directory.GetCurrentDirectory()' 현재 실행중인 프로그램의 위치 반환
FileInfo file = new FileInfo(Directory.GetCurrentDirectory() + "/test_dir/test2.txt");
if (!file.Exists)
{
FileStream fs = file.Create();
fs.Close();
}
// 파일 복사
// test_dir의 test2.txt를 t_path경로로 복사한다
// true = 덮어쓰기 허용 여부
// t_path 뒤의 이름을 변경하여 복사 하면서 파일 이름 변경도 한번에 가능하다.
System.IO.File.Copy(s_path.ToString() + @"\test2.txt", t_path.ToString() + @"\test_copy.txt", true);
System.IO.File.Copy(s_path.ToString() + @"\test2.txt", s_path2.ToString() + @"\test_copy.txt", true);
// 파일 이동
// t_path 뒤의 이름을 변경하여 복사 하면서 파일 이름 변경도 한번에 가능하다.
System.IO.File.Move(s_path.ToString() + @"\test2.txt", t_path.ToString() + @"\test_move.txt");
// 폴더 복사
// test_dir3번 폴더가 test_dir4번 폴더 아래 dir폴더로 이름이 바뀌어 이동(move)
System.IO.Directory.Move(s_path2.ToString(), t_path2.ToString() + @"/dir");
// 폴더 삭제
// true = 하위 폴더/파일 모두 삭제 여부
System.IO.Directory.Delete(t_path2.ToString(), true);
}
}
}
반응형