如何保存到一个文件的选择路径时,使用对话框?



我试过但不工作:

在windowmain . example .cs的底部,我添加了两个新的保存和加载方法:

private void SaveFile(string contentToSave, string fileName)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, fileName);
File.WriteAllText(saveFilePath, contentToSave);
}
private void LoadFile(string loadTo, string fileName)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, fileName); // add a file name to this path.  This is your full file path.
if (File.Exists(saveFilePath))
{
loadTo = File.ReadAllText(saveFilePath);
}
}

然后保存在两个地方:

private void btnRadarFolder_Click(object sender, RoutedEventArgs e)
{
VistaFolderBrowserDialog dlg = new VistaFolderBrowserDialog();
dlg.ShowNewFolderButton = true;
if (dlg.ShowDialog() == true)
{
SaveFile(textBoxRadarFolder.Text, "radarpath");
textBoxRadarFolder.Text = dlg.SelectedPath;
}
}
private void btnSatelliteFolder_Click(object sender, RoutedEventArgs e)
{
VistaFolderBrowserDialog dlg = new VistaFolderBrowserDialog();
dlg.ShowNewFolderButton = true;
if (dlg.ShowDialog() == true)
{
SaveFile(textBoxSatelliteFolder.Text, "satellitepath");
textBoxSatelliteFolder.Text = dlg.SelectedPath;
}
}

在顶部加载:

public MainWindow()
{
InitializeComponent();
LoadFile(textBoxRadarFolder.Text, "radarpath");
LoadFile(textBoxSatelliteFolder.Text, "satellitepath");

但是它什么都不做,没有错误,没有异常,只是在运行应用程序时没有将任何内容加载回文本框,我先选择了文件夹,但是没有。

更新:

保存正常

问题是加载:

在顶部,当我运行应用程序时:

public MainWindow()
{
InitializeComponent();
LoadFile(textBoxRadarFolder.Text, "radarpath.txt");
LoadFile(textBoxSatelliteFolder.Text, "satellitepath.txt");

但是在LoadFile方法的底部,我看到用于加载内容的控件文本由于某种原因是空的,即使我输入了两个文本框。要回读的文本为空:

变量loadTo为空,它应该是雷达和卫星的textBoxes。为什么loadTo为空?

private void LoadFile(string loadTo, string fileName)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, fileName); // add a file name to this path.  This is your full file path.
if (File.Exists(saveFilePath))
{
loadTo = File.ReadAllText(saveFilePath);
}
}

这是工作,我只是想知道的情况下,在LoadFile控件不是TextBox,但我们说,例如RichTextBox ?

它的工作现在为我的需要,但如果我想使LoadFile方法更通用的任何控件有文本属性的内容,如RichTextBox或标签?现在我用的是TextBox

LoadFile(textBoxRadarFolder, "radarpath.txt");
LoadFile(textBoxSatelliteFolder, "satellitepath.txt");

private void LoadFile(TextBox loadTo, string fileName)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, fileName); // add a file name to this path.  This is your full file path.
if (File.Exists(saveFilePath))
{
loadTo.Text = File.ReadAllText(saveFilePath);
}
}

最新更新