2015-01-11 4 views
0

나는 텍스트 필드 값에 따라 디렉토리를 생성하고 원하는 파일을 생성 된 폴더에 복사하고자하는 프로젝트에서 작업 중입니다 ... 지금까지 할 수있는 작업은 다음과 같습니다. ....파일을 생성 된 디렉토리에 복사

try 
{ 
    string id = textBox4.Text.Trim(); 
    // Directory.CreateDirectory("C:\\Users\\prashan\\Desktop\\"+id); 
    string source = null;     

    OpenFileDialog ofd = new OpenFileDialog(); 

    if (ofd.ShowDialog()==System.Windows.Forms.DialogResult.OK) 
    { 
     source = ofd.FileName; 
     MessageBox.Show(source); 
    } 

    string File_name = Path.GetFileName(source); 

    string destination = "C:\\Users\\prashan\\Desktop\\" + 
     System.IO.Directory.CreateDirectory(id) + File_name; 

    System.IO.File.Copy(source, destination); 
    MessageBox.Show("Done...."); 
} 
catch (Exception ex) 
{ 
    MessageBox.Show(ex.StackTrace); 
} 
+0

그래서 무엇이 문제입니까? 귀하의 게시물에 실제 질문이 표시되지 않습니다 ..? – quetzalcoatl

답변

1

을 디렉토리를 생성하고 생성 된 폴더에 파일 만 복사하면 다음 코드가 : 목적지 파일 이름에()

string destination = "C:\\Users\\prashan\\Desktop\\" 
    + System.IO.Directory.CreateDirectory(id) + File_name; 

당신은 CreateDirectory의 결과들을 연결됩니다, 잘못된 것입니다. 이 더 나은 것 Path.Combine()를 사용하여이 작업을 수행하는 가장 깨끗한 방법이 아니다

System.IO.Directory.CreateDirectory("C:\\Users\\prashan\\Desktop\\" + id); 
string destination = "C:\\Users\\prashan\\Desktop\\" + id + "\\" + File_name; 

,하지만 난 당신의 코드가 적게 변경을 원 대신, 당신은 다음과 같이 두 가지 작업으로이 분할 수 가능한 한.

+1

하지만 전체 경로라고 생각합니다. 단일 디렉토리 이름이 아닌가요? 아마도'destination = Path.Combine (System.IO.Directory.CreateDirectory ("C : \\ Users \\ Prashan \\ Desktop \\"+ id), File_name)'이 더 좋은 예 였을 것입니다. – Alan

+0

네, 그게 최고입니다. 그러나 MSDN이 "원래 경로"라고 말한 이후에 이것이 풀 패스 (fullpath) 였는지는 의심 스럽습니다. 그리고 위의 코드에서는 id = textbox.Text입니다. 나는 짧은 이름, 완전한 경로가 아니라는 것을 느낀다. 그러나 그것은 모두 단지 추측이다. 첫 번째 코멘트의 요점은 CreateDirectory()의 결과가 경로에 연결할 수 있다는 점이었습니다. 그래서 저는 여러분이''wrong''를 좀 더 부드럽게 만들 수 있다고 생각합니다. – quetzalcoatl

0

코드가 약간 변경되었습니다. 유효한 경로가되도록 대상 경로가 수정되었습니다.

try 
     { 
      string id = textBox4.Text.Trim(); 
      Directory.CreateDirectory("C:\\Users\\prashan\\Desktop\\"+id); 
      string source = null; 
      OpenFileDialog ofd = new OpenFileDialog(); 

      if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
      { 
       source = ofd.FileName; 
       MessageBox.Show(source); 

      } 

      string File_name = Path.GetFileName(source); 

      string destination = "C:\\Users\\prashan\\Desktop\\" + id +"\\"+ File_name; 


      System.IO.File.Copy(source, destination); 
      MessageBox.Show("Done...."); 

     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.StackTrace); 
     } 
+0

감사합니다. 설명이 추가되었습니다. –

관련 문제