1

我需要我的应用程序要求用户浏览到特定文件,保存该文件位置,然后从 TextBox 向其中写入一个字符串。

但是,我只需要我的最终用户在应用程序第一次启动时浏览到该文件。只有一次。

这就是我的困境,我如何让我的应用程序记住它是否是第一次启动?

4

3 回答 3

6

我认为您想要一个文件夹,而不是一个文件,但这不是重点。

您可以使用 UserSetting(请参阅项目属性、设置)并将其部署为空值或无效值。只有当您从设置中读取无效值时,您才会启动对话框。

这是基于每个用户的。

您可以在 .NET 中使用注册表,但您确实希望尽可能远离它。该库不在 System 命名空间中的事实是一个指标。

于 2009-08-15T17:40:19.193 回答
0

保存在注册表中选择的文件,或者保存在用户的 Documents and Settings 文件夹中的配置文件中。

要访问本地程序的路径,请使用:

string path = Environment.GetFolderPath(Environment.LocalApplicationData);
于 2009-08-15T17:38:37.713 回答
0

我将使用注册表为您的应用程序添加“SavedFileLocation”条目。

有关使用注册表的教程,请查看此处

然后您可以检查密钥是否存在,如果不存在对话框。
如果密钥存在,则应检查文件是否存在。如果该文件不存在,您可能应该将此信息提供给用户,并询问他们是否要在那里创建一个新文件,或者选择一个新位置。
否则,取该值并保留它以供运行时使用。

代码:

AppInitialization()
{
    RegistryKey appKey = Registry.CurrentUser.OpenSubKey(
        @"Software\YourName\YourApp"
        ?? Registry.CurrentUser.CreateSubKey( @"Software\YourName\YourApp" );


    this.fileLocation = appKey.GetValue( "SavedFileLocation" )
        ?? GetLocationFromDialog()
        ?? "DefaultFileInCurrentDirectory.txt";
}

private static string GetLocationFromDialog()
{
    string value = null;

    RegistryKey appKey = Registry.CurrentUser.OpenSubKey(
        @"Software\YourName\YourApp"
        ?? Registry.CurrentUser.CreateSubKey( @"Software\YourName\YourApp" );

    using( OpenFileDialog ofd = new OpenFileDialog() )
    {
        if( ofd.ShowDialog() == DialogResult.OK )
        {
            value = ofd.File;
            appKey.SetValue( "SavedFileLocation", value );
        }
    }

    return value;
}
于 2009-08-15T17:39:54.683 回答