Application.UserAppDataPath Propriedade

Definição

Obtém o caminho para os dados de aplicativo de um usuário.

public:
 static property System::String ^ UserAppDataPath { System::String ^ get(); };
public static string UserAppDataPath { get; }
member this.UserAppDataPath : string
Public Shared ReadOnly Property UserAppDataPath As String

Valor da propriedade

String

O caminho para os dados de aplicativo de um usuário.

Exemplos

O exemplo de código a seguir exibe dois formulários e sai do aplicativo quando ambos os formulários são fechados. Quando o aplicativo é iniciado e encerrado, a posição de cada formulário é lembrada. Este exemplo demonstra o uso da UserAppDataPath propriedade para armazenar dados do aplicativo para o usuário.

A classe MyApplicationContext herda ApplicationContext e mantém o controle quando cada formulário é fechado e sai do thread atual quando ambos estão. A classe armazena as posições de cada formulário para o usuário. Os dados de posição do formulário são armazenados em um arquivo intitulado Appdata.txt que é criado no local determinado por UserAppDataPath. O Main método chama Application.Run(context) para iniciar o aplicativo, considerando o ApplicationContext.

Esse código é um trecho do exemplo mostrado na visão geral da ApplicationContext classe. Alguns códigos não são mostrados para fins de brevidade. Consulte ApplicationContext a listagem de código inteira.

   MyApplicationContext()
   {
      _formCount = 0;
      
      // Handle the ApplicationExit event to know when the application is exiting.
      Application::ApplicationExit += gcnew EventHandler( this, &MyApplicationContext::OnApplicationExit );
      try
      {
         
         // Create a file that the application will store user specific data in.
         _userData = gcnew FileStream( String::Concat( Application::UserAppDataPath, "\\appdata.txt" ),FileMode::OpenOrCreate );
      }
      catch ( IOException^ e ) 
      {
         
         // Inform the user that an error occurred.
         MessageBox::Show( "An error occurred while attempting to show the application. The error is: {0}", dynamic_cast<String^>(e) );
         
         // Exit the current thread instead of showing the windows.
         ExitThread();
      }

      
      // Create both application forms and handle the Closed event
      // to know when both forms are closed.
      _form1 = gcnew AppForm1;
      _form1->Closed += gcnew EventHandler( this, &MyApplicationContext::OnFormClosed );
      _form1->Closing += gcnew CancelEventHandler( this, &MyApplicationContext::OnFormClosing );
      _formCount++;
      _form2 = gcnew AppForm2;
      _form2->Closed += gcnew EventHandler( this, &MyApplicationContext::OnFormClosed );
      _form2->Closing += gcnew CancelEventHandler( this, &MyApplicationContext::OnFormClosing );
      _formCount++;
      
      // Get the form positions based upon the user specific data.
      if ( ReadFormDataFromFile() )
      {
         
         // If the data was read from the file, set the form
         // positions manually.
         _form1->StartPosition = FormStartPosition::Manual;
         _form2->StartPosition = FormStartPosition::Manual;
         _form1->Bounds = _form1Position;
         _form2->Bounds = _form2Position;
      }

      
      // Show both forms.
      _form1->Show();
      _form2->Show();
   }

   void OnApplicationExit( Object^ /*sender*/, EventArgs^ /*e*/ )
   {
      
      // When the application is exiting, write the application data to the
      // user file and close it.
      WriteFormDataToFile();
      try
      {
         
         // Ignore any errors that might occur while closing the file handle.
         _userData->Close();
      }
      catch ( Exception^ ) 
      {
      }

   }

private:
private MyApplicationContext()
{
    _formCount = 0;

    // Handle the ApplicationExit event to know when the application is exiting.
    Application.ApplicationExit += new EventHandler(this.OnApplicationExit);

    try
    {
        // Create a file that the application will store user specific data in.
        _userData = new FileStream(Application.UserAppDataPath + "\\appdata.txt", FileMode.OpenOrCreate);
    }
    catch (IOException e)
    {
        // Inform the user that an error occurred.
        MessageBox.Show("An error occurred while attempting to show the application." +
                        "The error is:" + e.ToString());

        // Exit the current thread instead of showing the windows.
        ExitThread();
    }

    // Create both application forms and handle the Closed event
    // to know when both forms are closed.
    _form1 = new AppForm1();
    _form1.Closed += new EventHandler(OnFormClosed);
    _form1.Closing += new CancelEventHandler(OnFormClosing);
    _formCount++;

    _form2 = new AppForm2();
    _form2.Closed += new EventHandler(OnFormClosed);
    _form2.Closing += new CancelEventHandler(OnFormClosing);
    _formCount++;

    // Get the form positions based upon the user specific data.
    if (ReadFormDataFromFile())
    {
        // If the data was read from the file, set the form
        // positions manually.
        _form1.StartPosition = FormStartPosition.Manual;
        _form2.StartPosition = FormStartPosition.Manual;

        _form1.Bounds = _form1Position;
        _form2.Bounds = _form2Position;
    }

    // Show both forms.
    _form1.Show();
    _form2.Show();
}

private void OnApplicationExit(object sender, EventArgs e)
{
    // When the application is exiting, write the application data to the
    // user file and close it.
    WriteFormDataToFile();

    try
    {
        // Ignore any errors that might occur while closing the file handle.
        _userData.Close();
    }
    catch { }
}
Public Sub New()
    MyBase.New()
    _formCount = 0

    ' Handle the ApplicationExit event to know when the application is exiting.
    AddHandler Application.ApplicationExit, AddressOf OnApplicationExit

    Try
        ' Create a file that the application will store user specific data in.
        _userData = New FileStream(Application.UserAppDataPath + "\appdata.txt", FileMode.OpenOrCreate)

    Catch e As IOException
        ' Inform the user that an error occurred.
        MessageBox.Show("An error occurred while attempting to show the application." +
                        "The error is:" + e.ToString())

        ' Exit the current thread instead of showing the windows.
        ExitThread()
    End Try

    ' Create both application forms and handle the Closed event
    ' to know when both forms are closed.
    _form1 = New AppForm1()
    AddHandler _form1.Closed, AddressOf OnFormClosed
    AddHandler _form1.Closing, AddressOf OnFormClosing
    _formCount = _formCount + 1

    _form2 = New AppForm2()
    AddHandler _form2.Closed, AddressOf OnFormClosed
    AddHandler _form2.Closing, AddressOf OnFormClosing
    _formCount = _formCount + 1

    ' Get the form positions based upon the user specific data.
    If (ReadFormDataFromFile()) Then
        ' If the data was read from the file, set the form
        ' positions manually.
        _form1.StartPosition = FormStartPosition.Manual
        _form2.StartPosition = FormStartPosition.Manual

        _form1.Bounds = _form1Position
        _form2.Bounds = _form2Position
    End If

    ' Show both forms.
    _form1.Show()
    _form2.Show()
End Sub

Private Sub OnApplicationExit(ByVal sender As Object, ByVal e As EventArgs)
    ' When the application is exiting, write the application data to the
    ' user file and close it.
    WriteFormDataToFile()

    Try
        ' Ignore any errors that might occur while closing the file handle.
        _userData.Close()
    Catch
    End Try
End Sub

Comentários

Se um caminho não existir, um será criado no seguinte formato:

Caminho Base\CompanyName\ProductName\ProductVersion

Os dados armazenados nesse caminho fazem parte do perfil de usuário habilitado para roaming. Um usuário móvel funciona em mais de um computador em uma rede. O perfil de usuário de um usuário móvel é mantido em um servidor na rede e é carregado em um sistema quando o usuário faz logon. Para que um perfil de usuário seja considerado para roaming, o sistema operacional deve dar suporte a perfis móveis e ele deve ser habilitado.

Um caminho base típico é C:\Documents e Configurações\ username\Application Data. Esse caminho será diferente, no entanto, se o aplicativo Windows Forms for implantado usando ClickOnce. ClickOnce cria seu próprio diretório de dados de aplicativo isolado de todos os outros aplicativos. Para obter mais informações, confira Acessando dados locais e remotos em aplicativos ClickOnce.

Aplica-se a

Confira também