2017-02-07 4 views
0

Хорошо, я сделал это так далеко, но теперь я как бы застрял.SaveFileDialog вместо hardcoding save direction

Я создал форму окна, которая сохраняет и загружает оценки учащихся. Проблема в том, что направление сохранения и нагрузки жестко закодировано, я хочу использовать 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 

    } 

} 

Edit: Новый код с улучшениями (я не реализовали предложения 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

Open и Save диалоги на самом деле довольно легко.

Во-первых, вы будете инициализировать диалог:

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

Уход за разъяснением на моих и ответах Айбы? – 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 
       } 
      } 
     } 
    } 
} 
Смежные вопросы