728x90
반응형
728x170
■ 특정 디렉토리에서 유일한 파일명을 구하는 방법을 보여준다.
▶ Program.cs
namespace TestProject;
/// <summary>
/// 프로그램
/// </summary>
class Program
{
//////////////////////////////////////////////////////////////////////////////////////////////////// Method
////////////////////////////////////////////////////////////////////////////////////////// Static
//////////////////////////////////////////////////////////////////////////////// Private
#region 유일한 파일 경로 구하기 - GetUniqueFilePath(directoryPath, fileName, maximumTryCount)
/// <summary>
/// 유일한 파일 경로 구하기
/// </summary>
/// <param name="directoryPath">디렉토리 경로</param>
/// <param name="fileName">파일명</param>
/// <param name="maximumTryCount">최대 시도 카운트</param>
/// <returns>유일한 파일 경로</returns>
private static string GetUniqueFilePath(string directoryPath, string fileName, int maximumTryCount = 1024)
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
string fileExtension = Path.GetExtension(fileName);
HashSet<string> filePathHashSet = new HashSet<string>(Directory.GetFiles(directoryPath));
for(int i = 0; i < maximumTryCount; i++)
{
string targetFileName = (i == 0) ? fileName : string.Format("{0} ({1}){2}", fileNameWithoutExtension, i, fileExtension);
string targetFilePath = Path.Combine(directoryPath, targetFileName);
if(filePathHashSet.Contains(targetFilePath))
{
continue;
}
return targetFilePath;
}
throw new Exception($"{maximumTryCount}회 시도에도 유일한 파일명을 생성할 수 없습니다.");
}
#endregion
#region 프로그램 시작하기 - Main()
/// <summary>
/// 프로그램 시작하기
/// </summary>
private static void Main()
{
string directoryPath = "c:\\temp";
if(!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
for(int i = 0; i < 500; i++)
{
string filePath = GetUniqueFilePath(directoryPath, "test.txt");
using(FileStream stream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write))
{
Console.WriteLine($"{stream.Name} 파일이 생성되었습니다.");
}
}
}
#endregion
}
728x90
반응형
그리드형(광고전용)
댓글을 달아 주세요