我有一个带3个按钮的程序:“加载”,“保存”和“另存为”。 “保存”按钮最初显示为灰色,直到您“加载”文件(或“另存为”更好的版本中的文件)。
“Load”使用OpenFileDialog,“另存为”使用SaveFileDialog,而“Save”重用openFileDialog.FileName属性作为其StreamWriter的参数。
问题是,我可以“加载” - > “保存”文件,但我无法“加载” - > “保存” - > “另存为”,因为“保存”方法始终使用openFileDialog1.FileName,但正在使用的当前文件是saveAsFileDialog.FileName,因此它将保留在以前的文件中。
Tl; dr:我需要创建一个“string currentFileName”,它会在每次“加载”和“另存为”操作后更新,以便“保存”方法知道最近的文件是否为“加载”文件或者“另存为”之一。问题是我不知道如何在Form.cs中创建一个变量,它不仅可以在主Form方法中看到,而且可以在每个控件的事件处理程序生成的方法中看到。我认为我需要像全局变量这样的东西。
编辑:已添加代码。
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
string inputLine;
while ((inputLine = sr.ReadLine()) != null)
{
// some operations
}
}
}
catch (Exception ex)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(ex.Message);
}
}
// Enable "Save" Button
saveToolStripMenuItem.Enabled = true;
// currentFileName = openFileDialog1.FileName
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(saveFileDialog1.FileName))
{
// some operations
}
}
// currentFileName = saveFileDialog1.FileName
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
// openFileDialog1.FileName should be replaced by currentFileName
using (StreamWriter sw = new StreamWriter(openFileDialog1.FileName))
{
// some operations
}
}
}
}
答案 0 :(得分:0)
尝试这样的事情(请不要忘记添加第二个saveDialog):
public partial class Form1 : Form
{
String pathName;
public Form1()
{
InitializeComponent();
}
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pathname = openFileDialog1.FileName;
try
{
using (StreamReader sr = new StreamReader(pathname))
{
string inputLine;
while ((inputLine = sr.ReadLine()) != null)
{
// some operations
}
}
}
catch (Exception ex)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(ex.Message);
}
}
// Enable "Save" Button
saveToolStripMenuItem.Enabled = true;
// currentOpenedFile.FileName = openFileDialog1.FileName
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
pathname = saveFileDialog2.FileName;
using (StreamWriter sw = new StreamWriter(pathname))
{
// some operations
}
}
// currentOpenedFile.FileName = saveFileDialog1.FileName
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
// openFileDialog1.FileName should be replaced by currentOpenedFile.FileName
using (StreamWriter sw = new StreamWriter(pathname))
{
// some operations
}
}
}
}