2017-02-07 1 views
0

좋아, 지금까지 만들었지 만 지금은 고생 중입니다.저장 방향을 하드 코딩하는 대신 SaveFileDialog

저는 학생 성적을 저장하고로드하는 Windows 양식을 만들었습니다. 문제는 저장 및로드 방향이 하드 코딩되어 있으므로 파일을 저장하고로드하기 위해 filedialog를 사용하고 싶습니다.

나는 그 일을 확실하게하고 있지 않습니다. 어떤 아이디어?

private void btnLoad_Click(object sender, EventArgs e) 
    { 
     string filePath = @"C:\Users\grades.txt"; 
     if (File.Exists(filePath)) 
     { 
      StreamReader stream = new StreamReader(filePath); 
      txtResult.AppendText(stream.ReadToEnd()); 
      lblStatus.Text = "File Loaded"; 
     } 
     else 
      MessageBox.Show("There was a problem loading the file"); 
    } 

    private void btnSave_Click(object sender, EventArgs e) 
    { 
     lblStatus.Text = "Entry saved";//shows in status label 

     //string that specifies the location of the .txt file 
     string filePath = @"C:\Users\grades.txt"; 

     StreamWriter fileWriter = new StreamWriter(filePath, true);//creates new object of class StreamWriter to be able to write to file 

     //enters the information from the different textboxes to the file 
     fileWriter.WriteLine(txtLastName.Text + ", " + txtFirstName.Text + ":\t" + Convert.ToString(txtID.Text) + 
      "\t" + txtClass.Text + "\t" + txtGrades.Text); 

     fileWriter.Close();//closes filewriter 

    } 

} 

편집 : 개선과 새로운 코드 (나는 아직 Aybe의 제안을 구현하지 않은 경우).

나는 정신이 이상하지만 왜 작동하지 않는 것 같니? 내 마음 속에서 이것은 효과가 있지만 그렇지 않습니다. 내가 ... 파일 아무 일도 발생하지로드하려고 할 때

using System; 
using System.Windows.Forms; 
using System.IO; 

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

    private void btnOpen_Click(object sender, EventArgs e) 
    { 
     var dlg = new OpenFileDialog(); 

     dlg.InitialDirectory = "c:\\"; 
     dlg.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; 
     dlg.FilterIndex = 2; 
     dlg.RestoreDirectory = true; 

     if (dlg.ShowDialog() != DialogResult.OK) 
      return; 

    } 


    private void btnSave_Click(object sender, EventArgs e) 
    { 
     SaveFileDialog saveFileDialog1 = new SaveFileDialog(); 

     saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; 
     saveFileDialog1.FilterIndex = 2; 
     saveFileDialog1.RestoreDirectory = true; 

     if (saveFileDialog1.ShowDialog() == DialogResult.OK) 
     { 
      Stream myStream; 
      if ((myStream = saveFileDialog1.OpenFile()) != null) 
      { 
       StreamWriter fileWriter = new StreamWriter(myStream);//creates new object of class StreamWriter to be able to write to file 

       //enters the information from the different textboxes to the file 
       fileWriter.WriteLine(txtLastName.Text + ", " + txtFirstName.Text + ":\t" + Convert.ToString(txtID.Text) + 
        "\t" + txtClass.Text + "\t" + txtGrades.Text); 

       fileWriter.Close();//closes filewriter 
       myStream.Close(); 
      } 
     } 

    } 
} 

}

답변

-1

OpenSave 대화 상자가 실제로는 매우 쉽습니다. 그런 다음

SaveFileDialog saveFileDialog1 = new SaveFileDialog(); 

saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ; 
saveFileDialog1.FilterIndex = 2 ; 
saveFileDialog1.RestoreDirectory = true ; 

당신이 그것을 보여주고 자신의 경로를 탐색하는 사용자 대기하고 파일 이름을 입력합니다 :

첫째, 당신은 대화 상자를 초기화 할 수 있습니다

if(saveFileDialog1.ShowDialog() == DialogResult.OK) 
    { 
     if((myStream = saveFileDialog1.OpenFile()) != null) 
     { 
      // Code to write the stream goes here. 
      myStream.Close(); 
     } 
    } 
+0

광산과 Aybe의 대답에 es? – bwoogie

-1

을 @bwoogie 대답 이외에도 리소스를 쉽게 처분하기 위해 using 키워드를 활용하십시오.

using System; 
using System.IO; 
using System.Windows.Forms; 

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

     private void buttonOpen_Click(object sender, EventArgs e) 
     { 
      using (var dialog = new OpenFileDialog()) 
      { 
       if (dialog.ShowDialog() != DialogResult.OK) 
        return; 

       using (var reader = new StreamReader(dialog.OpenFile())) 
       { 
        // TODO read file 
       } 
      } 
     } 

     private void buttonSave_Click(object sender, EventArgs e) 
     { 
      using (var dialog = new SaveFileDialog()) 
      { 
       if (dialog.ShowDialog() != DialogResult.OK) 
        return; 

       using (var writer = new StreamWriter(dialog.OpenFile())) 
       { 
        // TODO save file 
       } 
      } 
     } 
    } 
} 
관련 문제