如何从 .dat 文件读取文件路径,然后在按下启动按钮时打开程序?

How Read File Path From a .dat file then open the program When Pressing The Launch Button?

我有一个问题,我无法让我的程序自动读取 .dat 中的给定文件路径,并准备好在按下启动文件时启动程序,而无需打开 openFileDialog 并每次都选择程序。

我在这里使用的代码是让用户第一次输入文件路径,然后创建一个文件路径.dat 文件,它适用于现在的问题。

using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                string path = Path.Combine(desktop, "LS\Fail-SafePath.dat");
                openFileDialog.InitialDirectory = filePath;
                openFileDialog.Filter = " PlayGTAV (*.exe)|PlayGTAV.exe";
                openFileDialog.FilterIndex = 1;
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    filePath = openFileDialog.FileName;

                    var fileStream = openFileDialog.OpenFile();

                    using (StreamReader reader = new StreamReader(fileStream))
                    {
                         fileContent = reader.ReadToEnd();

                    }

                    using (StreamWriter sw = File.CreateText(path))
                    {
                        sw.WriteLine(filePath);

                    }

在那之后我有一个开始按钮

private void panel21_MouseClick(object sender, MouseEventArgs e)
        {
            Process.Start(filePath);
        }

这在用户第一次使用时效果很好,但现在我希望它自动读取该 .dat 文件路径,而不必每次都向用户询问文件路径,我不知道该怎么做有待解决并需要帮助。

我想这样做:当按下启动按钮时(第一次之后)程序检查是否失败-SafePath.dat 如果是,它会从中读取行并启动程序从给定的路径而不打开 OpenFileDialog。

我正在使用 Visual Studio、Windows 表格。

如果它是应用程序始终需要的文件,那么就像您提到的那样:

I was thinking to do it like that: When Pressing the Launch button (After the first time) The Program Checks if the Fail-SafePath.dat Exists if Yes it reads the lines from it and starts the program from the given path without opening OpenFileDialog.

可以轻松工作。您可以让您的应用程序在默认位置查找它,如果不在那里,让您的用户 select 它。

另一个解决方案可能是使用类似 Application Settings or User Settings 的东西,这些值在 .NET 项目的执行之间持续存在。

根据您的完整应用程序设计,您还可以将文件路径和其他设置存储在某些数据库或其他数据存储中。有很多方法可以做到这一点。

编辑:进一步详细说明应用程序设置

应用程序设置非常容易read and write

你只需要创建你想要的,然后再尝试使用它们。

他们可以是created by:

  1. Open Visual Studio.
  2. In Solution Explorer, expand the Properties node of your project.
  3. Double-click the .settings file in which you want to add a new setting. The default name for this file is Settings.settings.
  4. In the Settings designer, set the Name, Value, Type, and Scope for your setting. Each row represents a single setting.

要读取您的设置:

this.FilePath= Properties.Settings.Default.FilePath;  

写入并保存设置:

Properties.Settings.Default.FilePath= Path.GetFullPath("importantFilePath");  

Properties.Settings.Default.Save();