2010-06-29 2 views
0

이 코드를 먼저 파일 이름이 존재하지 않는지 확인합니다. 이름이 바뀌면 둘 다 동일한 파일 이름 (test.txt)을 가지므로 내 테스트 파일이 제공되면 앱에 알게되었습니다. ### test.txt, # ~ test.txt는 잘못된 문자를 제거하지 않습니다.
만약 그렇다면, 나는 다른 foreach 루프로 이동하여 잘못된 문자를 특정 문자로 바꾼다. 코드가 도움이 될 것입니다.

감사합니다.

+2

당신은 [Path.GetInvalidFileNameChars] (http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx)와 [경로가 있다는 것을 알고있다. GetInvalidPathChars] (http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars.aspx)? – ChrisF

+0

실제로 저는 C#에 대해 매우 익숙하지 않았으므로이 사실을 알지 못했습니다. – yeahumok

+0

죄송합니다. 잘못된 길로 왔습니다. 불법 문자를 하드 코딩하는 대신 이러한 문자를 사용해야합니다. 언젠가 마이크로 소프트가 언젠가 그걸 바꿀지 모른다. – ChrisF

답변

2

File.Exists을 사용하면 파일이 이미 있는지 확인할 수 있습니다. 귀하의 예제에서 그래서 http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx

:

string sanitized = Path.Combine(pathOnly, sanitizedFileName); 
if (!System.IO.File.Exists(sanitized)) 
{ 
    // perform the move 
    System.IO.File.Move(files2, sanitized); 
} 
else 
{ 
    // perform other action 
} 

을 그리고 ChrisF이 유용하게 질문에 대한 코멘트 섹션에서 언급 한 바와 같이, 당신은 파일 이름이 유효한지 만들기위한 Path.GetInvalidFileNameCharsPath.GetInvalidPathChars을 사용할 수 있습니다 여기에 참조입니다.

+0

이 줄 다음에 오는 : string sanitized = Path.Combine (pathOnly, sanitizedFileName); ? – yeahumok

+0

@yeahumok - 예, 최근 편집을 참조하십시오. – dcp

1
if (System.IO.File.Exists(sanitized)) 
{ 
    // The file already exists! 
} 
0
int replacement = 0; 
while(File.Exists(sanitized)) 
{ 
    int lastDot = sanitized.LastIndexOf('.'); 
    if(lastDot < 0) 
     lastDot=sanitized.Length; 
    sanitized = String.Format("{0}{1}{2}", 
     sanitized.Substring(0,lastDot - (replacement>0?1:0)), 
     replacement++, 
     sanitized.Substring(lastDot) 
     ); 
} 
+0

이것은 이름이 바뀐 두 개의 입력 파일 이름이 동일한 출력 파일 이름과 충돌하는 문제를 해결하는 것으로 보입니다. – maxwellb

+0

downvotes로 의견을 말하십시오. 삭제 또는 고칠 수 있습니다. 감사합니다. – maxwellb