Condividi tramite


How to: Access the Local File System in Trusted Applications

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Trusted applications can access System.IO and related types that are otherwise unavailable. This enables you to access user files directly without using the OpenFileDialog and SaveFileDialog classes. However, in Silverlight 4 and earlier, you can access only files in user folders, specifically the MyDocuments, MyMusic, MyPictures, and MyVideos folders.

NoteNote:

These folders are distinct from the Windows 7 Libraries named Documents, Music, Pictures, and Videos. These library folders typically combine the contents of the user folders with other folders, such as shared media folders. However, trusted applications cannot access non-user folders except through the OpenFileDialog and SaveFileDialog classes.

Starting in Silverlight 5, trusted applications have unrestricted access to the local file system, although in-browser trusted applications are still subject to browser security restrictions. For more information, see Trusted Applications.

The following topic demonstrates how to access files in user folders.

NoteNote:

Silverlight for Windows Phone Silverlight for Windows Phone and Silverlight 3 do not support trusted applications.

Procedures

To access files in user folders

  • Use the supported APIs as you would in the desktop framework, but use the previously-indicated values of the System.Environment.SpecialFolder enumeration to construct paths. The following example demonstrates the required usage.

    Private Sub TestIO()
        If (Application.Current.HasElevatedPermissions) Then
            Dim myDocuments As String = Environment.GetFolderPath( _
                Environment.SpecialFolder.MyDocuments)
            Dim filename As String = "test.txt"
            Dim path As String = _
                System.IO.Path.Combine(myDocuments, filename)
            If File.Exists(path) Then
                Dim contents As String = File.ReadAllText(path)
                MessageBox.Show(contents)
            End If
        End If
    End Sub
    
    private void TestIO()
    {
        if (Application.Current.HasElevatedPermissions)
        {
            string myDocuments = Environment.GetFolderPath(
                Environment.SpecialFolder.MyDocuments);
            string filename = "test.txt";
            string path = System.IO.Path.Combine(myDocuments, filename);
            if (File.Exists(path))
            {
                string contents = File.ReadAllText(path);
                MessageBox.Show(contents);
            }
        }
    }
    

For more examples, see the StreamReader, StreamWriter, and DirectoryInfo classes.

Security

For security considerations in trusted applications, see Trusted Applications.