좋아, 지금까지 만들었지 만 지금은 고생 중입니다.저장 방향을 하드 코딩하는 대신 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();
}
}
}
}
}
광산과 Aybe의 대답에 es? – bwoogie