Question

I need my application to ask the user to browse to a particular file, save that files location and subsequently write a string from a TextBox to it.

However, I only need my end-user to browse to the file the first time the application launches. Only once.

Here lies my dilemma, how can I have my application remember if it was the first time it launched?

Was it helpful?

Solution

I think you want a folder, not a file, but that is besides the point.

You can use a UserSetting (See Project properties, Settings) and deploy it with an empty or invalid value. Only when you read the invalid value from settings do you start the Dialog.

This is on a per-user basis.

You can use the Registry in .NET but you really want to stay away from that as much as possible. The fact that the library is not in a System namespace is an indicator.

OTHER TIPS

Save the file chosen in the registry, or in a configuration file in the user's Documents and Settings folder.

To get to your local program's path, use:

string path = Environment.GetFolderPath(Environment.LocalApplicationData);

I would use the Registry to add an entry for "SavedFileLocation" for your application.

For a tutorial on using the registry, check here.

Then you can check if the key exists, if not present the dialog.
If the key exists, you should check for existence of the file. If the file does not exist, you should probably present this information to the user, and ask them if they want to create a new file there, or choose a new location.
Otherwise, take that value and keep it for runtime.

CODE:

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top