如何解决在C#中存储目录路径
我必须使文件夹路径可重用。当我打开一个文件夹时,该程序必须保存一次它的目录,以便单击该按钮时无需在文件夹中导航就可以立即重新打开它。 我以为我创建了一个字符串并将路径目录存储了一段时间。
我该如何进行这项工作? 我现在将文件路径存储在文本框中:
OpenFileDialog openFileDialog1 = new OpenFileDialog
{
InitialDirectory = @"D:\",Title = "browse Text Files",CheckFileExists = true,CheckPathExists = true,DefaultExt = "txt",Filter = "txt files (*.txt)|*.txt",FilterIndex = 2,RestoreDirectory = true,ReadOnlyChecked = true,ShowReadOnly = true
};
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
}
解决方法
您可以使用static string
变量:
private const string initDefaultPath = @"D:\"; // <-- initial default folder path
private static string prevFolderPath = initDefaultPath;
//Let's suppose a button click event
public void Button1_Click(object sender,EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog
{
InitialDirectory = string.IsNullOrWhiteSpace(prevFolderPath)
? initDefaultPath
: prevFolderPath,Title = "Browse Text Files",CheckFileExists = true,CheckPathExists = true,DefaultExt = "txt",Filter = "txt files (*.txt)|*.txt",FilterIndex = 2,RestoreDirectory = true,ReadOnlyChecked = true,ShowReadOnly = true
};
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
prevFolderPath = Path.GetDirectoryName(openFileDialog1.FileName);
}
}
,
我认为您所需要的是一种形式来记住例如上次使用的路径。进行此操作的官方方法是进入项目属性,然后进入设置,并添加新的字符串类型的设置值以存储路径或文件名信息。
然后您还需要两件事。
-
根据需要将文本框绑定到属性以用于显示。您可以在
.NET Core
应用程序中手动完成此操作,方法是将以下代码添加到Form1.Designer.cs
文件中private void InitializeComponent() { ... this.textBox1.DataBindings.Add( new System.Windows.Forms.Binding("Text",global::WindowsFormsApp1.Properties.Settings.Default,"lastPath",true,System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); ... }
或者如果您使用的是
.NET Framework
,那么 ApplicationSettings 下的文本框会有一个UI选项。 -
表单关闭时保存表单所需的最后一项。这是通过处理
完成的FormClosing
事件private void Form1_FormClosing(object sender,FormClosingEventArgs e) { Properties.Settings.Default.Save(); }
现在,您的代码可以读取和写入文本框所需的内容,并且设置文件将同步同步处理。例如,在文件打开操作中,如果您希望将最后一个板条存储在文本框中,请执行以下操作:
private void button1_Click(object sender,EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog
{
InitialDirectory = textBox1.Text,ShowReadOnly = true
};
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = System.IO.Path.GetDirectoryName(openFileDialog1.FileName);
}
这样,每次启动应用程序时,它都会记住文本框的内容
请注意,该应用程序将在以下位置创建一个设置XML文件:
,您可以使用Path.GetFullPath
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = Path.GetFullPath(openFileDialog1.FileName);
}
,
您可以使用Jamiec所说的将路径存储在变量中
然后您将使用system.io.open()第二次打开文件
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。