Хорошо, я сделал это так далеко, но теперь я как бы застрял.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();
}
}
}
}
}
Уход за разъяснением на моих и ответах Айбы? – bwoogie