2016-08-12 1 views
-3

기본적으로 특정 파일을 비우거나 심지어 삭제하는 프로그램을 만들려고합니다. 즉,이 파일은 macromedia 폴더를지나 3 ~ 4 개 정도 폴더에 저장됩니다. 누군가를 위해 다른 이름의 폴더가 될 수 있습니다. 그래서 string [] 파일이 그런 식으로 이루어지며 기본적으로 매크로 미디어 폴더 다음의 모든 폴더에서 기본적으로 "FlashGame.sol"을 확인합니다.(파일 삭제/비우기) C#

내가 도움이 필요한 부분에 댓글을 달았습니다. 기본적으로 파일의 내용을 비우거나 파일을 삭제해야합니다.

private void button1_Click(object sender, EventArgs e) 
    { 
     string path = textBox1.Text + "/AppData/Roaming/Macromedia"; //the person using the program has to type in the beginning of the directory, C:/Users/Mike for example 
     bool Exists = Directory.Exists(path); 
     try 
     { 
      if (Exists) 
      { 
       string[] files = Directory.GetFiles(path, "*FlashGame.sol", SearchOption.AllDirectories); 
       string[] array = files; 
       for (int i = 0; i < array.Length; i++) 
       { 
        string info; 
        string text = array[i]; 
        using (StreamReader streamReader = new StreamReader(text)) 
        { 
         info = streamReader.ReadToEnd(); 
         //erase the contents of the file here or even delete it 
        } 
       } 
      } 

     } 
     catch 
     { 
      MessageBox.Show("The given directory was not found", "Error", MessageBoxButtons.OK); 
     } 
    } 
+0

'File.Delete()'? – David

+0

@David 예, 매개 변수에 경로 문자열을 포함해야합니다. "파일"을 넣으면 작동하지 않습니다 (경로 변수가 가득 차지 않았기 때문에 "경로"를 넣을 수 없습니다). 경로), 아마도 파일은 string []이기 때문에 기본적으로 내가 붙어있는 부분이다. C#을 처음 접했어. 미안. – user6037051

+0

'text' 변수에는 무엇이 있습니까? – David

답변

0

당신은 이런 식으로 파일을 지울 수 있습니다 :

System.IO.File.WriteAllText(@"file.path",string.Empty); 

그래서 당신은 아마 당신의 코드 변경해야합니다 : 또한 Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)에서 살펴

string[] files = Directory.GetFiles(path, "*FlashGame.sol", SearchOption.AllDirectories); 
foreach (var file in files) 
{ 
    System.IO.File.WriteAllText(file, string.Empty); 
} 

을의 APPDATA 디렉토리를 제공합니다 현재 사용자의

도 절대로 catching a Exception without handling it correctly입니다. 디렉토리가 Exists 변수를 통해 존재하는 경우 이미 알고 있습니다.

0
string path = Environment.ExpandEnvironmentVariables(@"%AppData%\Macromedia\"); // Example C:\Users\Mike\AppData\Roaming\Macromedia\ 

if (Directory.Exists(path)) { 
    string[] files = Directory.EnumerateFiles(path, "*FlashGame.sol", SearchOption.AllDirectories); 

    foreach (string file in files) { 
     try { 
      File.Delete(file); 
     } 
     catch (Exception ex) { 
      MessageBox.Show(ex.Message); 
     } 
    } 
}