2010-06-28 4 views
1

Windows Form 애플리케이션이 있습니다. 이 응용 프로그램이하는 일은 사용자가 파일 이름을 바꿀 드라이브/폴더를 탐색하도록합니다. 이 앱은 "유효하지 않은"문자 (RegEx 패턴으로 정의)가있는 파일의 이름을 바꿉니다.내 버튼을 클래스에 호출하는 데 문제가 발생했습니다.

내가 원하는 것은 사용자가 사용할 드라이브/폴더를 결정한 후 이름을 바꿀 드라이브/폴더의 사용자 파일을 보여주는 datagridview를 팝업하는 것입니다. 그런 다음 사용자는 단추를 클릭하여 실제로 파일의 이름을 바꿉니다. DriveRecursion_Results.cs에서 내 버튼 코드를 설정하는 데 문제가 있습니다. 아무도 나를 도울 수 있습니까? 코드 plz - 나는 이것에 아주 새롭고 이해하기 위해 살펴볼 구문이 필요하다.

Form1 코드 :

namespace FileMigration2 
{ 
public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     FolderSelect("Please select:"); 

    } 

    public string FolderSelect(string txtPrompt) 
    { 
     //Value to be returned 
     string result = string.Empty; 

     //Now, we want to use the path information to population our folder selection initial location 
     string initialPathDir = (@"C:\"); 
     System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(initialPathDir); 
     FolderBrowserDialog FolderSelect = new FolderBrowserDialog(); 
     FolderSelect.SelectedPath = info.FullName; 
     FolderSelect.Description = txtPrompt; 
     FolderSelect.ShowNewFolderButton = true; 

     if (FolderSelect.ShowDialog() == DialogResult.OK) 
     { 
      string retPath = FolderSelect.SelectedPath; 
      if (retPath == null) 
      { 
       retPath = ""; 
      } 
      DriveRecursion_Results dw = new DriveRecursion_Results(); 
      dw.Show(); 
      dw.DriveRecursion(retPath); 

      result = retPath; 

     } 

     return result; 

    } 





    } 
} 

DriveRecursion_Results.cs 코드 : [버튼 내가 도움이 필요 여기에있다!]

namespace FileMigration2 
{ 
public partial class DriveRecursion_Results : Form 
{ 
    public DriveRecursion_Results() 
    { 
     InitializeComponent(); 

    } 

    private void listView1_SelectedIndexChanged(object sender, EventArgs e) 
    { 

    } 

    public void DriveRecursion(string retPath) 
    { 
     //recurse through files. Let user press 'ok' to move onto next step   
     // string[] files = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories); 

     string pattern = " *[\\~#%&*{}/<>?|\"-]+ *"; 
     //string replacement = ""; 
     Regex regEx = new Regex(pattern); 

     string[] fileDrive = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories); 
     List<string> filePath = new List<string>(); 


     dataGridView1.Rows.Clear(); 
     try 
     { 
      foreach (string fileNames in fileDrive) 
      { 

       if (regEx.IsMatch(fileNames)) 
       { 
        string fileNameOnly = Path.GetFileName(fileNames); 
        string pathOnly = Path.GetDirectoryName(fileNames); 

        DataGridViewRow dgr = new DataGridViewRow(); 
        filePath.Add(fileNames); 
        dgr.CreateCells(dataGridView1); 
        dgr.Cells[0].Value = pathOnly; 
        dgr.Cells[1].Value = fileNameOnly; 
        dataGridView1.Rows.Add(dgr); 
        filePath.Add(fileNames); 
       } 

       else 
       { 
        DataGridViewRow dgr2 = new DataGridViewRow(); 
        dgr2.Cells[0].Value = "No Files To Clean Up"; 
        dgr2.Cells[1].Value = ""; 
       } 

      } 
     } 
     catch (Exception e) 
     { 
      StreamWriter sw = new StreamWriter(retPath + "ErrorLog.txt"); 
      sw.Write(e); 

     } 

    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     //What do i type in here to call my FileCleanUp method??? 
    } 




} 

SanitizeFileNames.cs 코드 :

namespace FileMigration2 
{ 
    public class SanitizeFileNames 
{ 

    public static void FileCleanup(List<string>filePath) 
    { 
     string regPattern = "*[\\~#%&*{}/<>?|\"-]+*"; 
     string replacement = ""; 
     Regex regExPattern = new Regex(regPattern); 


     foreach (string files2 in filePath) 
     { 
      try 
      { 
       string filenameOnly = Path.GetFileName(files2); 
       string pathOnly = Path.GetDirectoryName(files2); 
       string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement); 
       string sanitized = Path.Combine(pathOnly, sanitizedFileName); 
       //write to streamwriter 
       System.IO.File.Move(files2, sanitized); 

      } 
      catch (Exception ex) 
      { 
      //write to streamwriter 

      } 

     } 

     } 

    } 
} 
    } 

도움을 주시면 감사하겠습니다.

감사합니다 :)

+0

그냥 정적 메서드를 호출하는 데 문제가 있습니까? –

+0

잘 여기에 있습니다. 내 DriveRecursion 메서드에서 filePath를 호출하고 싶습니다 -하지만 어떻게 해야할지 모르겠습니다. 파일 경로에 filecleanup을 수행 할 수 있도록 필자는이를 단추에 전달해야합니다. – yeahumok

답변

2

public partial class DriveRecursion_Results : Form { 
    List<string> filePath; 

및 driveRecursion 방법에

, 그냥
filePath = new List<string>(); 

과 동작 버튼 방식에서

, 왜 당신이하지 않는 사용 넣어

if(filePath != null) 
     SanitizeFileNames.FileCleanup(filePath); 
  1. filePath.Add 번으로 전화 하시겠습니까?

  2. 'else'의 위치가 잘못되었습니다.

  3. dgr2은 무엇입니까?

+0

나는 이것을 디버깅했고, 나에게 main에 filePath를 선언하는 것은 거의 의미가 없었다. 그것은 null로 남았습니다. filePath의 요점은 파일의 이름을 바꿀 수 있도록 FileCleanup의 경로를 제공하는 것입니다. dgr2는 내 DataGridView의 또 다른 인스턴스입니다. 나는 이것이 필요한지 확실하지 않지만, 사용자가 지정하는 드라이브/폴더에서 정리할 것이 없기 때문에 거기에 가지고있다. – yeahumok

+0

위에서 작성한 것처럼 filePath를 클래스 멤버로 선언해야합니다. 그 이유는 한 번에 목록을 만들고 다른 시간 (버튼을 누를 때)에 실제 정리를 수행하기 때문입니다. 따라서 데이터는 그동안 지속되는 어딘가에 저장되어야합니다. null이 계속되면 DriveRecursion() 메서드에서 설정하지 않았거나 두 번 선언했을 수 있습니다. –

관련 문제