IsolatedStorageFileStream Classe

Definição

Expõe um arquivo no armazenamento isolado.Exposes a file within isolated storage.

public ref class IsolatedStorageFileStream : System::IO::Stream
public ref class IsolatedStorageFileStream : System::IO::FileStream
public class IsolatedStorageFileStream : System.IO.Stream
public class IsolatedStorageFileStream : System.IO.FileStream
[System.Runtime.InteropServices.ComVisible(true)]
public class IsolatedStorageFileStream : System.IO.FileStream
type IsolatedStorageFileStream = class
    inherit Stream
type IsolatedStorageFileStream = class
    inherit FileStream
[<System.Runtime.InteropServices.ComVisible(true)>]
type IsolatedStorageFileStream = class
    inherit FileStream
Public Class IsolatedStorageFileStream
Inherits Stream
Public Class IsolatedStorageFileStream
Inherits FileStream
Herança
IsolatedStorageFileStream
Herança
IsolatedStorageFileStream
Atributos

Exemplos

O aplicativo de console a seguir demonstra como você pode usar IsolatedStorageFile e IsolatedStorageFileStream para gravar dados em um arquivo de armazenamento isolado.The following console application demonstrates how you can use IsolatedStorageFile and IsolatedStorageFileStream to write data to an Isolated Storage file. O usuário é solicitado a fazer logon.The user is requested to log in. Se o usuário for um novo usuário, uma URL de notícias e uma URL esportiva serão registradas como preferências pessoais no armazenamento isolado.If the user is a new user, a News URL and a Sports URL are recorded as personal preferences in Isolated Storage. Se o usuário for um usuário que está retornando, as preferências atuais do usuário serão exibidas.If the user is a returning user, the user's current preferences are displayed. Os exemplos de código usados em todo esse namespace são apresentados no contexto deste aplicativo de exemplo.The code examples used throughout this namespace are presented in the context of this sample application. Você pode usar o utilitário Storeadm.exe (ferramenta de armazenamento isolado) para listar e remover os arquivos de armazenamento isolado que são criados com esse aplicativo de console.You can use the Storeadm.exe (Isolated Storage Tool) utility to list and remove the Isolated Storage files that are created with this console application.

// This sample demonstrates methods of classes found in the System.IO IsolatedStorage namespace.
using namespace System;
using namespace System::IO;
using namespace System::IO::IsolatedStorage;
using namespace System::Security::Policy;
using namespace System::Security::Permissions;

public ref class LoginPrefs
{
private:
   String^ userName;
   String^ newsUrl;
   String^ sportsUrl;
   bool newPrefs;

public:

   [SecurityPermissionAttribute(SecurityAction::Demand, Flags=SecurityPermissionFlag::UnmanagedCode)]
   bool GetPrefsForUser()
   {
      try
      {
         
         // Retrieve an IsolatedStorageFile for the current Domain and Assembly.
         IsolatedStorageFile^ isoFile = IsolatedStorageFile::GetStore( static_cast<IsolatedStorageScope>(IsolatedStorageScope::User | IsolatedStorageScope::Assembly | IsolatedStorageScope::Domain), (Type^)nullptr, nullptr );
         IsolatedStorageFileStream^ isoStream = gcnew IsolatedStorageFileStream( this->userName,FileMode::Open,FileAccess::ReadWrite,isoFile );
         
         // farThe code executes to this point only if a file corresponding to the username exists.
         // Though you can perform operations on the stream, you cannot get a handle to the file.
         try
         {
            IntPtr aFileHandle = isoStream->Handle;
            Console::WriteLine( "A pointer to a file handle has been obtained. {0} {1}", aFileHandle, aFileHandle.GetHashCode() );
         }
         catch ( Exception^ e ) 
         {
            
            // Handle the exception.
            Console::WriteLine( "Expected exception" );
            Console::WriteLine( e->ToString() );
         }

         StreamReader^ reader = gcnew StreamReader( isoStream );
         
         // Read the data.
         this->NewsUrl = reader->ReadLine();
         this->SportsUrl = reader->ReadLine();
         reader->Close();
         isoFile->Close();
         isoStream->Close();
         return false;
      }
      catch ( Exception^ e ) 
      {
         
         // Expected exception if a file cannot be found. This indicates that we have a new user.
         String^ errorMessage = e->ToString();
         return true;
      }

   }


   bool GetIsoStoreInfo()
   {
      
      // Get a User store with type evidence for the current Domain and the Assembly.
      IsolatedStorageFile^ isoFile = IsolatedStorageFile::GetStore( static_cast<IsolatedStorageScope>(IsolatedStorageScope::User | IsolatedStorageScope::Assembly | IsolatedStorageScope::Domain), System::Security::Policy::Url::typeid, System::Security::Policy::Url::typeid );
      
      array<String^>^dirNames = isoFile->GetDirectoryNames( "*" );
      array<String^>^fileNames = isoFile->GetFileNames( "*" );
      
      // List directories currently in this Isolated Storage.
      if ( dirNames->Length > 0 )
      {
         for ( int i = 0; i < dirNames->Length; ++i )
         {
            Console::WriteLine( "Directory Name: {0}", dirNames[ i ] );

         }
      }

      
      // List the files currently in this Isolated Storage.
      // The list represents all users who have personal preferences stored for this application.
      if ( fileNames->Length > 0 )
      {
         for ( int i = 0; i < fileNames->Length; ++i )
         {
            Console::WriteLine( "File Name: {0}", fileNames[ i ] );

         }
      }

      
      isoFile->Close();
      return true;
   }


   double SetPrefsForUser()
   {
      try
      {
         
         IsolatedStorageFile^ isoFile;
         isoFile = IsolatedStorageFile::GetUserStoreForDomain();
         
         // Open or create a writable file.
         IsolatedStorageFileStream^ isoStream = gcnew IsolatedStorageFileStream( this->userName,FileMode::OpenOrCreate,FileAccess::Write,isoFile );
         StreamWriter^ writer = gcnew StreamWriter( isoStream );
         writer->WriteLine( this->NewsUrl );
         writer->WriteLine( this->SportsUrl );
         
         // Calculate the amount of space used to record the user's preferences.
         double d = isoFile->CurrentSize / isoFile->MaximumSize;
         Console::WriteLine( "CurrentSize = {0}", isoFile->CurrentSize.ToString() );
         Console::WriteLine( "MaximumSize = {0}", isoFile->MaximumSize.ToString() );
         writer->Close();
         isoFile->Close();
         isoStream->Close();
         return d;
         
      }
      catch ( Exception^ e ) 
      {      
         // Add code here to handle the exception.
         Console::WriteLine( e->ToString() );
         return 0.0;
      }

   }


   void DeleteFiles()
   {
      
      try
      {
         IsolatedStorageFile^ isoFile = IsolatedStorageFile::GetStore( static_cast<IsolatedStorageScope>(IsolatedStorageScope::User | IsolatedStorageScope::Assembly | IsolatedStorageScope::Domain), System::Security::Policy::Url::typeid, System::Security::Policy::Url::typeid );
         array<String^>^dirNames = isoFile->GetDirectoryNames( "*" );
         array<String^>^fileNames = isoFile->GetFileNames( "*" );
         
         // List the files currently in this Isolated Storage.
         // The list represents all users who have personal
         // preferences stored for this application.
         if ( fileNames->Length > 0 )
         {
            for ( int i = 0; i < fileNames->Length; ++i )
            {
               
               //Delete the files.
               isoFile->DeleteFile( fileNames[ i ] );

            }
            fileNames = isoFile->GetFileNames( "*" );
         }
         isoFile->Close();
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( e->ToString() );
      }

   }


   // This method deletes directories in the specified Isolated Storage, after first 
   // deleting the files they contain. In this example, the Archive directory is deleted. 
   // There should be no other directories in this Isolated Storage.
   void DeleteDirectories()
   {
      try
      {
         IsolatedStorageFile^ isoFile = IsolatedStorageFile::GetStore( static_cast<IsolatedStorageScope>(IsolatedStorageScope::User | IsolatedStorageScope::Assembly | IsolatedStorageScope::Domain), System::Security::Policy::Url::typeid, System::Security::Policy::Url::typeid );
         array<String^>^dirNames = isoFile->GetDirectoryNames( "*" );
         array<String^>^fileNames = isoFile->GetFileNames( "Archive\\*" );
         
         // Delete the current files within the Archive directory.
         if ( fileNames->Length > 0 )
         {
            for ( int i = 0; i < fileNames->Length; ++i )
            {
               
               //delete files
               isoFile->DeleteFile( String::Concat("Archive\\", fileNames[ i ]) );

            }
            fileNames = isoFile->GetFileNames( "Archive\\*" );
         }
         if ( dirNames->Length > 0 )
         {
            for ( int i = 0; i < dirNames->Length; ++i )
            {
               
               // Delete the Archive directory.
               isoFile->DeleteDirectory( dirNames[ i ] );

            }
         }
         dirNames = isoFile->GetDirectoryNames( "*" );
         isoFile->Remove();
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( e->ToString() );
      }

   }


   double SetNewPrefsForUser()
   {
      try
      {
         Byte inputChar;
         IsolatedStorageFile^ isoFile = IsolatedStorageFile::GetStore( static_cast<IsolatedStorageScope>(IsolatedStorageScope::User | IsolatedStorageScope::Assembly | IsolatedStorageScope::Domain), System::Security::Policy::Url::typeid, System::Security::Policy::Url::typeid );
         
         // If this is not a new user, archive the old preferences and 
         // overwrite them using the new preferences.
         if (  !this->NewPrefs )
         {
            if ( isoFile->GetDirectoryNames( "Archive" )->Length == 0 )
                        isoFile->CreateDirectory( "Archive" );
            else
            {
               
               // This is the stream to which data will be written.
               IsolatedStorageFileStream^ source = gcnew IsolatedStorageFileStream( this->userName,FileMode::OpenOrCreate,isoFile );
               
               // This is the stream from which data will be read.
               Console::WriteLine( "Is the source file readable?  {0}", (source->CanRead ? (String^)"true" : "false") );
               Console::WriteLine( "Creating new IsolatedStorageFileStream for Archive." );
               
               // Open or create a writable file.
               IsolatedStorageFileStream^ target = gcnew IsolatedStorageFileStream( String::Concat("Archive\\",this->userName),FileMode::OpenOrCreate,FileAccess::Write,FileShare::Write,isoFile );
               
               Console::WriteLine( "Is the target file writable? {0}", (target->CanWrite ? (String^)"true" : "false") );
               
               // Stream the old file to a new file in the Archive directory.
               if ( source->IsAsync && target->IsAsync )
               {
                  
                  // IsolatedStorageFileStreams cannot be asynchronous.  However, you
                  // can use the asynchronous BeginRead and BeginWrite functions
                  // with some possible performance penalty.
                  Console::WriteLine( "IsolatedStorageFileStreams cannot be asynchronous." );
               }
               else
               {
                  
                  Console::WriteLine( "Writing data to the new file." );
                  while ( source->Position < source->Length )
                  {
                     inputChar = (Byte)source->ReadByte();
                     target->WriteByte( (Byte)source->ReadByte() );
                  }
                  
                  // Determine the size of the IsolatedStorageFileStream
                  // by checking its Length property.
                  Console::WriteLine( "Total Bytes Read: {0}", source->Length.ToString() );
                  
               }
               
               // After you have read and written to the streams, close them.
               target->Close();
               source->Close();
            }
         }
         
         // Open or create a writable file, no larger than 10k
         IsolatedStorageFileStream^ isoStream = gcnew IsolatedStorageFileStream( this->userName,FileMode::OpenOrCreate,FileAccess::Write,FileShare::Write,10240,isoFile );
         
         isoStream->Position = 0; // Position to overwrite the old data.
         
         StreamWriter^ writer = gcnew StreamWriter( isoStream );
         
         // Update the data based on the new inputs.
         writer->WriteLine( this->NewsUrl );
         writer->WriteLine( this->SportsUrl );
         
         // Calculate the amount of space used to record this user's preferences.
         double d = isoFile->CurrentSize / isoFile->MaximumSize;
         Console::WriteLine( "CurrentSize = {0}", isoFile->CurrentSize.ToString() );
         Console::WriteLine( "MaximumSize = {0}", isoFile->MaximumSize.ToString() );
         
         // StreamWriter.Close implicitly closes isoStream.
         writer->Close();
         isoFile->Close();
         return d;
      }
      catch ( Exception^ e ) 
      {
         Console::WriteLine( e->ToString() );
         return 0.0;
      }

   }

   LoginPrefs( String^ aUserName )
   {
      userName = aUserName;
      newPrefs = GetPrefsForUser();
   }


   property String^ NewsUrl 
   {
      String^ get()
      {
         return newsUrl;
      }

      void set( String^ value )
      {
         newsUrl = value;
      }

   }

   property String^ SportsUrl 
   {
      String^ get()
      {
         return sportsUrl;
      }

      void set( String^ value )
      {
         sportsUrl = value;
      }

   }

   property bool NewPrefs 
   {
      bool get()
      {
         return newPrefs;
      }

   }

};

void GatherInfoFromUser( LoginPrefs^ lp )
{
   Console::WriteLine( "Please enter the URL of your news site." );
   lp->NewsUrl = Console::ReadLine();
   Console::WriteLine( "Please enter the URL of your sports site." );
   lp->SportsUrl = Console::ReadLine();
}

int main()
{
   
   // Prompt the user for their username.
   Console::WriteLine( "Enter your login ID:" );
   
   // Does no error checking.
   LoginPrefs^ lp = gcnew LoginPrefs( Console::ReadLine() );
   if ( lp->NewPrefs )
   {
      Console::WriteLine( "Please set preferences for a new user." );
      GatherInfoFromUser( lp );
      
      // Write the new preferences to storage.
      double percentUsed = lp->SetPrefsForUser();
      Console::WriteLine( "Your preferences have been written. Current space used is {0}%", percentUsed );
   }
   else
   {
      Console::WriteLine( "Welcome back." );
      Console::WriteLine( "Your preferences have expired, please reset them." );
      GatherInfoFromUser( lp );
      lp->SetNewPrefsForUser();
      Console::WriteLine( "Your news site has been set to {0}\n and your sports site has been set to {1}.", lp->NewsUrl, lp->SportsUrl );
   }

   lp->GetIsoStoreInfo();
   Console::WriteLine( "Enter 'd' to delete the IsolatedStorage files and exit, or press any other key to exit without deleting files." );
   String^ consoleInput = Console::ReadLine();
   if ( consoleInput->Equals( "d" ) )
   {
      lp->DeleteFiles();
      lp->DeleteDirectories();
   }
}

// This sample demonstrates methods of classes found in the System.IO IsolatedStorage namespace.
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Security.Policy;
using Microsoft.Win32.SafeHandles;
using System.Security.Permissions;

[assembly: CLSCompliantAttribute(true)]

class ConsoleApp
{
    [STAThread]
    static void Main(string[] args)
    {

        // Prompt the user for their username.

        Console.WriteLine("Login:");

        // Does no error checking.
        LoginPrefs lp = new LoginPrefs(Console.ReadLine());

        if (lp.NewPrefs)
        {
            Console.WriteLine("Please set preferences for a new user.");
            GatherInfoFromUser(lp);

            // Write the new preferences to storage.
            double percentUsed = lp.SetPrefsForUser();
            Console.WriteLine("Your preferences have been written. Current space used is " + percentUsed.ToString() + " %");
        }
        else
        {
            Console.WriteLine("Welcome back.");

            Console.WriteLine("Your preferences have expired, please reset them.");
            GatherInfoFromUser(lp);
            lp.SetNewPrefsForUser();

            Console.WriteLine("Your news site has been set to {0}\n and your sports site has been set to {1}.", lp.NewsUrl, lp.SportsUrl);
        }
        lp.GetIsoStoreInfo();
        Console.WriteLine("Enter 'd' to delete the IsolatedStorage files and exit, or press any other key to exit without deleting files.");
        string consoleInput = Console.ReadLine();
        if (consoleInput.ToLower() == "d")
        {
            lp.DeleteFiles();
            lp.DeleteDirectories();
        }
    }

    static void GatherInfoFromUser(LoginPrefs lp)
    {
        Console.WriteLine("Please enter the URL of your news site.");
        lp.NewsUrl = Console.ReadLine();
        Console.WriteLine("Please enter the URL of your sports site.");
        lp.SportsUrl = Console.ReadLine();
    }
}
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
public class LoginPrefs
{
    public LoginPrefs(string myUserName)
    {
        userName = myUserName;
        myNewPrefs = GetPrefsForUser();
    }
    string userName;

    string myNewsUrl;
    public string NewsUrl
    {
        get { return myNewsUrl; }
        set { myNewsUrl = value; }
    }

    string mySportsUrl;
    public string SportsUrl
    {
        get { return mySportsUrl; }
        set { mySportsUrl = value; }
    }
    bool myNewPrefs;
    public bool NewPrefs
    {
        get { return myNewPrefs; }
    }

    private bool GetPrefsForUser()
    {
        try
        {

            // Retrieve an IsolatedStorageFile for the current Domain and Assembly.
            IsolatedStorageFile isoFile =
                IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
                IsolatedStorageScope.Assembly |
                IsolatedStorageScope.Domain,
                null,
                null);

            IsolatedStorageFileStream isoStream =
                new IsolatedStorageFileStream("substituteUsername",
                System.IO.FileMode.Open,
                System.IO.FileAccess.Read,
                 System.IO.FileShare.Read);

            // The code executes to this point only if a file corresponding to the username exists.
            // Though you can perform operations on the stream, you cannot get a handle to the file.

            try
            {

                SafeFileHandle aFileHandle = isoStream.SafeFileHandle;
                Console.WriteLine("A pointer to a file handle has been obtained. "
                    + aFileHandle.ToString() + " "
                    + aFileHandle.GetHashCode());
            }

            catch (Exception e)
            {
                // Handle the exception.
                Console.WriteLine("Expected exception");
                Console.WriteLine(e);
            }

            StreamReader reader = new StreamReader(isoStream);
            // Read the data.
            this.NewsUrl = reader.ReadLine();
            this.SportsUrl = reader.ReadLine();
            reader.Close();
            isoFile.Close();
            return false;
        }
        catch (System.IO.FileNotFoundException)
        {
            // Expected exception if a file cannot be found. This indicates that we have a new user.
            return true;
        }
    }
    public bool GetIsoStoreInfo()
    {
        // Get a User store with type evidence for the current Domain and the Assembly.
        IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
            IsolatedStorageScope.Assembly |
            IsolatedStorageScope.Domain,
            typeof(System.Security.Policy.Url),
            typeof(System.Security.Policy.Url));

        String[] dirNames = isoFile.GetDirectoryNames("*");
        String[] fileNames = isoFile.GetFileNames("*");

        // List directories currently in this Isolated Storage.
        if (dirNames.Length > 0)
        {
            for (int i = 0; i < dirNames.Length; ++i)
            {
                Console.WriteLine("Directory Name: " + dirNames[i]);
            }
        }

        // List the files currently in this Isolated Storage.
        // The list represents all users who have personal preferences stored for this application.
        if (fileNames.Length > 0)
        {
            for (int i = 0; i < fileNames.Length; ++i)
            {
                Console.WriteLine("File Name: " + fileNames[i]);
            }
        }

        isoFile.Close();
        return true;
    }

    public double SetPrefsForUser()
    {
        try
        {
            IsolatedStorageFile isoFile;
            isoFile = IsolatedStorageFile.GetUserStoreForDomain();

            // Open or create a writable file.
            IsolatedStorageFileStream isoStream =
                new IsolatedStorageFileStream(this.userName,
                FileMode.OpenOrCreate,
                FileAccess.Write,
                isoFile);

            StreamWriter writer = new StreamWriter(isoStream);
            writer.WriteLine(this.NewsUrl);
            writer.WriteLine(this.SportsUrl);
            // Calculate the amount of space used to record the user's preferences.
            double d = isoFile.CurrentSize / isoFile.MaximumSize;
            Console.WriteLine("CurrentSize = " + isoFile.CurrentSize.ToString());
            Console.WriteLine("MaximumSize = " + isoFile.MaximumSize.ToString());
            // StreamWriter.Close implicitly closes isoStream.
            writer.Close();
            isoFile.Dispose();
            isoFile.Close();
            return d;
        }
        catch (IsolatedStorageException ex)
        {
            // Add code here to handle the exception.
            Console.WriteLine(ex);
            return 0.0;
        }
    }

    public void DeleteFiles()
    {
        try
        {
            IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
                IsolatedStorageScope.Assembly |
                IsolatedStorageScope.Domain,
                typeof(System.Security.Policy.Url),
                typeof(System.Security.Policy.Url));

            String[] dirNames = isoFile.GetDirectoryNames("*");
            String[] fileNames = isoFile.GetFileNames("*");

            // List the files currently in this Isolated Storage.
            // The list represents all users who have personal
            // preferences stored for this application.
            if (fileNames.Length > 0)
            {
                for (int i = 0; i < fileNames.Length; ++i)
                {
                    // Delete the files.
                    isoFile.DeleteFile(fileNames[i]);
                }
                // Confirm that no files remain.
                fileNames = isoFile.GetFileNames("*");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
    // This method deletes directories in the specified Isolated Storage, after first
    // deleting the files they contain. In this example, the Archive directory is deleted.
    // There should be no other directories in this Isolated Storage.
    public void DeleteDirectories()
    {
        try
        {
            IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
                IsolatedStorageScope.Assembly |
                IsolatedStorageScope.Domain,
                typeof(System.Security.Policy.Url),
                typeof(System.Security.Policy.Url));
            String[] dirNames = isoFile.GetDirectoryNames("*");
            String[] fileNames = isoFile.GetFileNames("Archive\\*");

            // Delete all the files currently in the Archive directory.

            if (fileNames.Length > 0)
            {
                for (int i = 0; i < fileNames.Length; ++i)
                {
                    // Delete the files.
                    isoFile.DeleteFile("Archive\\" + fileNames[i]);
                }
                // Confirm that no files remain.
                fileNames = isoFile.GetFileNames("Archive\\*");
            }

            if (dirNames.Length > 0)
            {
                for (int i = 0; i < dirNames.Length; ++i)
                {
                    // Delete the Archive directory.
                }
            }
            dirNames = isoFile.GetDirectoryNames("*");
            isoFile.Remove();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
    public double SetNewPrefsForUser()
    {
        try
        {
            byte inputChar;
            IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
                IsolatedStorageScope.Assembly |
                IsolatedStorageScope.Domain,
                typeof(System.Security.Policy.Url),
                typeof(System.Security.Policy.Url));

            // If this is not a new user, archive the old preferences and
            // overwrite them using the new preferences.
            if (!this.myNewPrefs)
            {
                if (isoFile.GetDirectoryNames("Archive").Length == 0)
                {
                    isoFile.CreateDirectory("Archive");
                }
                else
                {

                    IsolatedStorageFileStream source =
                        new IsolatedStorageFileStream(this.userName, FileMode.OpenOrCreate,
                        isoFile);
                    // This is the stream from which data will be read.
                    Console.WriteLine("Is the source file readable? " + (source.CanRead ? "true" : "false"));
                    Console.WriteLine("Creating new IsolatedStorageFileStream for Archive.");

                    // Open or create a writable file.
                    IsolatedStorageFileStream target =
                        new IsolatedStorageFileStream("Archive\\ " + this.userName,
                        FileMode.OpenOrCreate,
                        FileAccess.Write,
                        FileShare.Write,
                        isoFile);
                    Console.WriteLine("Is the target file writable? " + (target.CanWrite ? "true" : "false"));
                    // Stream the old file to a new file in the Archive directory.
                    if (source.IsAsync && target.IsAsync)
                    {
                        // IsolatedStorageFileStreams cannot be asynchronous.  However, you
                        // can use the asynchronous BeginRead and BeginWrite functions
                        // with some possible performance penalty.

                        Console.WriteLine("IsolatedStorageFileStreams cannot be asynchronous.");
                    }

                    else
                    {
                        Console.WriteLine("Writing data to the new file.");
                        while (source.Position < source.Length)
                        {
                            inputChar = (byte)source.ReadByte();
                            target.WriteByte(inputChar);
                        }

                        // Determine the size of the IsolatedStorageFileStream
                        // by checking its Length property.
                        Console.WriteLine("Total Bytes Read: " + source.Length);
                    }

                    // After you have read and written to the streams, close them.
                    target.Close();
                    source.Close();
                }
            }

            // Open or create a writable file with a maximum size of 10K.
            IsolatedStorageFileStream isoStream =
                new IsolatedStorageFileStream(this.userName,
                FileMode.OpenOrCreate,
                FileAccess.Write,
                FileShare.Write,
                10240,
                isoFile);
            isoStream.Position = 0;  // Position to overwrite the old data.
            StreamWriter writer = new StreamWriter(isoStream);
            // Update the data based on the new inputs.
            writer.WriteLine(this.NewsUrl);
            writer.WriteLine(this.SportsUrl);

            // Calculate the amount of space used to record this user's preferences.
            double d = isoFile.CurrentSize / isoFile.MaximumSize;
            Console.WriteLine("CurrentSize = " + isoFile.CurrentSize.ToString());
            Console.WriteLine("MaximumSize = " + isoFile.MaximumSize.ToString());
            // StreamWriter.Close implicitly closes isoStream.
            writer.Close();
            isoFile.Close();

            return d;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            return 0.0;
        }
    }
}

'This sample demonstrates methods of classes found in the System.IO IsolatedStorage namespace.
Imports System.IO
Imports System.IO.IsolatedStorage
Imports System.Security.Policy
Imports Microsoft.Win32.SafeHandles
Imports System.Security.Permissions



Namespace ISOCS
    _
    Class ConsoleApp


        <STAThread()> _
       Overloads Shared Sub Main(ByVal args() As String)

            ' Prompt the user for their username.
            Console.WriteLine("Enter your login ID:")

            ' Does no error checking.
            Dim lp As New LoginPrefs(Console.ReadLine())

            If lp.NewPrefs Then
                Console.WriteLine("Please set preferences for a new user.")
                GatherInfoFromUser(lp)

                ' Write the new preferences to storage.
                Dim percentUsed As Double = lp.SetPrefsForUser()
                Console.WriteLine(("Your preferences have been written. Current space used is " & percentUsed.ToString() & " %"))
            Else
                Console.WriteLine("Welcome back.")

                Console.WriteLine("Your preferences have expired, please reset them.")
                GatherInfoFromUser(lp)
                lp.SetNewPrefsForUser()

                Console.WriteLine("Your news site has been set to {0}" & ControlChars.Cr & " and your sports site has been set to {1}.", lp.NewsUrl, lp.SportsUrl)
            End If
            lp.GetIsoStoreInfo()
            Console.WriteLine("Enter 'd' to delete the IsolatedStorage files and exit, or press any other key to exit without deleting files.")
            Dim consoleInput As String = Console.ReadLine()
            If consoleInput.ToLower() = "d" Then
                lp.DeleteFiles()
                lp.DeleteDirectories()
            End If
        End Sub


        Shared Sub GatherInfoFromUser(ByVal lp As LoginPrefs)
            Console.WriteLine("Please enter the URL of your news site.")
            lp.NewsUrl = Console.ReadLine()
            Console.WriteLine("Please enter the URL of your sports site.")
            lp.SportsUrl = Console.ReadLine()
        End Sub
    End Class
    _

    <SecurityPermissionAttribute(SecurityAction.Demand, Flags:=SecurityPermissionFlag.UnmanagedCode)> _
    Public Class LoginPrefs

        Public Sub New(ByVal myUserName As String)
            userName = myUserName
            myNewPrefs = GetPrefsForUser()
        End Sub
        Private userName As String

        Private myNewsUrl As String

        Public Property NewsUrl() As String
            Get
                Return myNewsUrl
            End Get
            Set(ByVal Value As String)
                myNewsUrl = Value
            End Set
        End Property
        Private mySportsUrl As String

        Public Property SportsUrl() As String
            Get
                Return mySportsUrl
            End Get
            Set(ByVal Value As String)
                mySportsUrl = Value
            End Set
        End Property
        Private myNewPrefs As Boolean

        Public ReadOnly Property NewPrefs() As Boolean
            Get
                Return myNewPrefs
            End Get
        End Property

        Private Function GetPrefsForUser() As Boolean
            Try
                ' Retrieve an IsolatedStorageFile for the current Domain and Assembly.
                Dim isoFile As IsolatedStorageFile = _
                    IsolatedStorageFile.GetStore(IsolatedStorageScope.User _
                    Or IsolatedStorageScope.Assembly _
                    Or IsolatedStorageScope.Domain, Nothing, Nothing)

                Dim isoStream As New IsolatedStorageFileStream("substituteUsername", System.IO.FileMode.Open, _
                    System.IO.FileAccess.Read, System.IO.FileShare.Read)
                ' farThe code executes to this point only if a file corresponding to the username exists.
                ' Though you can perform operations on the stream, you cannot get a handle to the file.
                Try

                    Dim aFileHandle As SafeFileHandle = isoStream.SafeFileHandle
                    Console.WriteLine(("A pointer to a file handle has been obtained. " & aFileHandle.ToString() & " " & aFileHandle.GetHashCode()))

                Catch ex As Exception
                    ' Handle the exception.
                    Console.WriteLine("Expected exception")
                    Console.WriteLine(ex.ToString())
                End Try

                Dim reader As New StreamReader(isoStream)
                ' Read the data.
                Me.NewsUrl = reader.ReadLine()
                Me.SportsUrl = reader.ReadLine()
                reader.Close()
                isoFile.Close()
                Return False
            Catch ex As System.IO.FileNotFoundException
                ' Expected exception if a file cannot be found. This indicates that we have a new user.
                Return True
            End Try
        End Function 'GetPrefsForUser

        Public Function GetIsoStoreInfo() As Boolean
            Try
                'Get a User store with type evidence for the current Domain and the Assembly.
                Dim isoFile As IsolatedStorageFile = _
                    IsolatedStorageFile.GetStore(IsolatedStorageScope.User Or _
                    IsolatedStorageScope.Assembly Or IsolatedStorageScope.Domain, _
                    GetType(System.Security.Policy.Url), GetType(System.Security.Policy.Url))
                Dim dirNames As String() = isoFile.GetDirectoryNames("*")
                Dim fileNames As String() = isoFile.GetFileNames("*")
                Dim name As String

                ' List directories currently in this Isolated Storage.
                If dirNames.Length > 0 Then

                    For Each name In dirNames
                        Console.WriteLine("Directory Name: " & name)
                    Next name
                End If

                ' List the files currently in this Isolated Storage.
                ' The list represents all users who have personal preferences stored for this application.
                If fileNames.Length > 0 Then

                    For Each name In fileNames
                        Console.WriteLine("File Name: " & name)
                    Next name
                End If
                isoFile.Close()
                Return True
            Catch ex As Exception
                Console.WriteLine(ex.ToString())
            End Try
        End Function 'GetIsoStoreInfo

        Public Function SetPrefsForUser() As Double
            Try
                Dim isoFile As IsolatedStorageFile
                isoFile = IsolatedStorageFile.GetUserStoreForDomain()

                ' Open or create a writable file.
                Dim isoStream As New IsolatedStorageFileStream(Me.userName, FileMode.OpenOrCreate, _
                    FileAccess.Write, isoFile)

                Dim writer As New StreamWriter(isoStream)
                writer.WriteLine(Me.NewsUrl)
                writer.WriteLine(Me.SportsUrl)
                ' Calculate the amount of space used to record the user's preferences.
                Dim d As Double = Convert.ToDouble(isoFile.CurrentSize) / Convert.ToDouble(isoFile.MaximumSize)
                Console.WriteLine(("CurrentSize = " & isoFile.CurrentSize.ToString()))
                Console.WriteLine(("MaximumSize = " & isoFile.MaximumSize.ToString()))
                ' StreamWriter.Close implicitly closes isoStream.
                writer.Close()
                isoFile.Dispose()
                isoFile.Close()
                Return d
            Catch ex As Exception
                ' Add code here to handle the exception.
                Console.WriteLine(ex)
                Return 0.0
            End Try
        End Function 'SetPrefsForUser


        Public Sub DeleteFiles()
            Try
                Dim isoFile As IsolatedStorageFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User Or _
                    IsolatedStorageScope.Assembly Or IsolatedStorageScope.Domain, _
                    GetType(System.Security.Policy.Url), GetType(System.Security.Policy.Url))
                Dim name As String
                Dim dirNames As String() = isoFile.GetDirectoryNames("*")
                Dim fileNames As String() = isoFile.GetFileNames("*")
                ' List the files currently in this Isolated Storage.
                ' The list represents all users who have personal
                ' preferences stored for this application.
                If fileNames.Length > 0 Then
                    For Each name In fileNames
                        ' Delete the files.
                        isoFile.DeleteFile(name)
                    Next name
                    'Confirm no files are left.
                    fileNames = isoFile.GetFileNames("*")
                End If
            Catch ex As Exception
                Console.WriteLine(ex.ToString())
            End Try
        End Sub

        ' This method deletes directories in the specified Isolated Storage, after first 
        ' deleting the files they contain. In this example, the Archive directory is deleted. 
        ' There should be no other directories in this Isolated Storage.
        Public Sub DeleteDirectories()
            Try
                Dim isoFile As IsolatedStorageFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User _
                    Or IsolatedStorageScope.Assembly Or IsolatedStorageScope.Domain, _
                    GetType(System.Security.Policy.Url), GetType(System.Security.Policy.Url))
                Dim name As String
                Dim dirNames As String() = isoFile.GetDirectoryNames("*")
                Dim fileNames As String() = isoFile.GetFileNames("Archive\*")
                ' Delete all the files currently in the Archive directory.
                If fileNames.Length > 0 Then
                    For Each name In fileNames
                        isoFile.DeleteFile(("Archive\" & name))
                    Next name
                    'Confirm no files are left.
                    fileNames = isoFile.GetFileNames("Archive\*")
                End If
                If dirNames.Length > 0 Then
                    For Each name In dirNames
                        ' Delete the Archive directory.
                        isoFile.DeleteDirectory(name)
                    Next name
                End If
                dirNames = isoFile.GetDirectoryNames("*")
                isoFile.Remove()
            Catch ex As Exception
                Console.WriteLine(ex.ToString())
            End Try
        End Sub

        Public Function SetNewPrefsForUser() As Double
            Try
                Dim inputChar As Byte
                Dim isoFile As IsolatedStorageFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User Or _
                    IsolatedStorageScope.Assembly Or IsolatedStorageScope.Domain, _
                    GetType(System.Security.Policy.Url), GetType(System.Security.Policy.Url))

                ' If this is not a new user, archive the old preferences and 
                ' overwrite them using the new preferences.
                If Not Me.myNewPrefs Then
                    If isoFile.GetDirectoryNames("Archive").Length = 0 Then
                        isoFile.CreateDirectory("Archive")
                    Else

                        Dim source As New IsolatedStorageFileStream(Me.userName, FileMode.OpenOrCreate, isoFile)
                        Dim canWrite, canRead As Boolean
                        ' This is the stream from which data will be read.
                        If source.CanRead Then canRead = True Else canRead = False
                        Console.WriteLine("Is the source file readable? " & canRead)
                        Console.WriteLine("Creating new IsolatedStorageFileStream for Archive.")
                        ' Open or create a writable file.
                        Dim target As New IsolatedStorageFileStream("Archive\ " & Me.userName, _
                             FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write, isoFile)
                        ' This is the stream to which data will be written.
                        If target.CanWrite Then canWrite = True Else canWrite = False
                        Console.WriteLine("Is the target file writable? " & canWrite)
                        target.SetLength(0)  'rewind the target file

                        ' Stream the old file to a new file in the Archive directory.
                        If source.IsAsync And target.IsAsync Then
                            ' IsolatedStorageFileStreams cannot be asynchronous.  However, you
                            ' can use the asynchronous BeginRead and BeginWrite functions
                            ' with some possible performance penalty.
                            Console.WriteLine("IsolatedStorageFileStreams cannot be asynchronous.")
                        Else
                            Console.WriteLine("Writing data to the new file.")
                            While source.Position < source.Length
                                inputChar = CByte(source.ReadByte())
                                target.WriteByte(inputChar)
                            End While

                            ' Determine the size of the IsolatedStorageFileStream
                            ' by checking its Length property.
                            Console.WriteLine(("Total Bytes Read: " & source.Length))
                        End If

                        ' After you have read and written to the streams, close them.	
                        target.Close()
                        source.Close()
                    End If
                End If
                ' Open or create a writable file with a maximum size of 10K.
                Dim isoStream As New IsolatedStorageFileStream(Me.userName, FileMode.OpenOrCreate, _
                    FileAccess.Write, FileShare.Write, 10240, isoFile)
                isoStream.SetLength(0) 'Position to overwrite the old data.
                Dim writer As New StreamWriter(isoStream)
                ' Update the data based on the new inputs.
                writer.WriteLine(Me.NewsUrl)
                writer.WriteLine(Me.SportsUrl)

                '  Calculate the amount of space used to record this user's preferences.
                Dim d As Double = Convert.ToDouble(isoFile.CurrentSize) / Convert.ToDouble(isoFile.MaximumSize)
                Console.WriteLine(("CurrentSize = " & isoFile.CurrentSize.ToString()))
                Console.WriteLine(("MaximumSize = " & isoFile.MaximumSize.ToString()))
                ' StreamWriter.Close implicitly closes isoStream.
                writer.Close()
                isoFile.Close()

                Return d
            Catch ex As Exception
                Console.WriteLine(ex.ToString())
                Return 0.0
            End Try
        End Function 'SetNewPrefsForUser
    End Class
End Namespace 'ISOCS

Comentários

Use essa classe para ler, gravar e criar arquivos no armazenamento isolado.Use this class to read, write and create files in isolated storage.

Como essa classe FileStream se estende, você pode usar uma instância do IsolatedStorageFileStream na maioria das situações em que um FileStream pode ser usado de outra forma, por exemplo, para construir um StreamReader ou StreamWriter .Since this class extends FileStream, you can use an instance of IsolatedStorageFileStream in most situations where a FileStream might otherwise be used, such as to construct a StreamReader or StreamWriter.

Esse tipo implementa a interface IDisposable.This type implements the IDisposable interface. Quando você terminar de usar o tipo, deverá descartá-lo direta ou indiretamente.When you have finished using the type, you should dispose of it either directly or indirectly. Para descartar o tipo diretamente, chame o método Dispose dele em um bloco try/catch.To dispose of the type directly, call its Dispose method in a try/catch block. Para descartá-lo indiretamente, use um constructo de linguagem como using ( em C#) ou Using (em Visual Basic).To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). Saiba mais na seção "Como usar um objeto que implementa IDisposable" no tópico da interface IDisposable.For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

Importante

O armazenamento isolado não está disponível para aplicativos Windows Store 8.xWindows 8.x Store.Isolated storage is not available for Windows Store 8.xWindows 8.x Store apps. Em vez disso, use as classes de dados de aplicativos nos namespaces Windows.Storage incluídos na API Windows RuntimeWindows Runtime para armazenar dados e arquivos locais.Instead, use the application data classes in the Windows.Storage namespaces included in the Windows RuntimeWindows Runtime API to store local data and files. Para saber mais, confira Dados de aplicativo no Centro de Desenvolvimento do Windows.For more information, see Application data in the Windows Dev Center.

Construtores

IsolatedStorageFileStream(String, FileMode)

Inicializa uma nova instância de um objeto IsolatedStorageFileStream fornecendo acesso ao arquivo designado pelo path no mode especificado.Initializes a new instance of an IsolatedStorageFileStream object giving access to the file designated by path in the specified mode.

IsolatedStorageFileStream(String, FileMode, FileAccess)

Inicializa uma nova instância da classe IsolatedStorageFileStream dando acesso ao arquivo designado pelo path, no mode especificado, com o tipo de access solicitado.Initializes a new instance of the IsolatedStorageFileStream class giving access to the file designated by path, in the specified mode, with the kind of access requested.

IsolatedStorageFileStream(String, FileMode, FileAccess, FileShare)

Inicializa uma nova instância da classe IsolatedStorageFileStream dando acesso ao arquivo designado pelo path, especificado no mode, com o arquivo especificado access, usando o modo de compartilhamento de arquivo especificado pelo share.Initializes a new instance of the IsolatedStorageFileStream class giving access to the file designated by path, in the specified mode, with the specified file access, using the file sharing mode specified by share.

IsolatedStorageFileStream(String, FileMode, FileAccess, FileShare, Int32)

Inicializa uma nova instância da classe IsolatedStorageFileStream dando acesso ao arquivo designado pelo path, especificado na mode, com o arquivo especificado access, usando o modo de compartilhamento de arquivo especificado pelo share com o buffersize especificado.Initializes a new instance of the IsolatedStorageFileStream class giving access to the file designated by path, in the specified mode, with the specified file access, using the file sharing mode specified by share, with the buffersize specified.

IsolatedStorageFileStream(String, FileMode, FileAccess, FileShare, Int32, IsolatedStorageFile)

Inicializa uma nova instância da classe IsolatedStorageFileStream dando acesso ao arquivo designado pelo path, no mode especificado, com o arquivo especificado access, usando o modo de compartilhamento de arquivo especificado pelo share, com o buffersize especificado e no contexto do IsolatedStorageFile especificado por isf.Initializes a new instance of the IsolatedStorageFileStream class giving access to the file designated by path, in the specified mode, with the specified file access, using the file sharing mode specified by share, with the buffersize specified, and in the context of the IsolatedStorageFile specified by isf.

IsolatedStorageFileStream(String, FileMode, FileAccess, FileShare, IsolatedStorageFile)

Inicializa uma nova instância da classe IsolatedStorageFileStream dando acesso ao arquivo designado por path, no mode especificado, com o arquivo access especificado, usando o modo de compartilhamento de arquivo especificado por share e no contexto do IsolatedStorageFile especificado por isf.Initializes a new instance of the IsolatedStorageFileStream class giving access to the file designated by path, in the specified mode, with the specified file access, using the file sharing mode specified by share, and in the context of the IsolatedStorageFile specified by isf.

IsolatedStorageFileStream(String, FileMode, FileAccess, IsolatedStorageFile)

Inicializa uma nova instância da classe IsolatedStorageFileStream dando acesso ao arquivo designado por path no mode especificado, com o arquivo access especificado e no contexto do IsolatedStorageFile especificado por isf.Initializes a new instance of the IsolatedStorageFileStream class giving access to the file designated by path in the specified mode, with the specified file access, and in the context of the IsolatedStorageFile specified by isf.

IsolatedStorageFileStream(String, FileMode, IsolatedStorageFile)

Inicializa uma nova instância da classe de IsolatedStorageFileStream dando acesso ao arquivo designado por path, no mode especificado e no contexto do IsolatedStorageFile especificado por isf.Initializes a new instance of the IsolatedStorageFileStream class giving access to the file designated by path, in the specified mode, and in the context of the IsolatedStorageFile specified by isf.

Propriedades

CanRead

Obtém um valor booliano que indica se o arquivo pode ser lido.Gets a Boolean value indicating whether the file can be read.

CanSeek

Obtém um valor booliano que indica se há suporte para operações de busca.Gets a Boolean value indicating whether seek operations are supported.

CanTimeout

Obtém um valor que determina se o fluxo atual pode atingir o tempo limite.Gets a value that determines whether the current stream can time out.

(Herdado de Stream)
CanWrite

Obtém um valor booliano que indica se você pode gravar no arquivo.Gets a Boolean value indicating whether you can write to the file.

Handle
Obsoleto.
Obsoleto.
Obsoleto.

Obtém o identificador de arquivo para o arquivo que o objeto IsolatedStorageFileStream atual encapsula.Gets the file handle for the file that the current IsolatedStorageFileStream object encapsulates. Não é permitido acessar essa propriedade em um objeto IsolatedStorageFileStream e gera um IsolatedStorageException.Accessing this property is not permitted on an IsolatedStorageFileStream object, and throws an IsolatedStorageException.

IsAsync

Obtém um valor booliano que indica se o objeto IsolatedStorageFileStream foi aberto de forma assíncrona ou síncrona.Gets a Boolean value indicating whether the IsolatedStorageFileStream object was opened asynchronously or synchronously.

Length

Obtém o comprimento do objeto IsolatedStorageFileStream.Gets the length of the IsolatedStorageFileStream object.

Name

Obtém o caminho absoluto do arquivo aberto no FileStream.Gets the absolute path of the file opened in the FileStream.

(Herdado de FileStream)
Position

Obtém ou define a posição atual do objeto IsolatedStorageFileStream atual.Gets or sets the current position of the current IsolatedStorageFileStream object.

ReadTimeout

Obtém ou define um valor, em milissegundos, que determina por quanto tempo o fluxo tentará realizar a leitura antes do tempo limite.Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out.

(Herdado de Stream)
SafeFileHandle

Obtém um objeto SafeFileHandle que representa o identificador de arquivo do sistema operacional para o arquivo que o objeto IsolatedStorageFileStream atual encapsula.Gets a SafeFileHandle object that represents the operating system file handle for the file that the current IsolatedStorageFileStream object encapsulates.

SafeFileHandle

Obtém um objeto SafeFileHandle que representa o identificador de arquivo do sistema operacional para o arquivo que o objeto FileStream atual encapsula.Gets a SafeFileHandle object that represents the operating system file handle for the file that the current FileStream object encapsulates.

(Herdado de FileStream)
WriteTimeout

Obtém ou define um valor, em milissegundos, que determina por quanto tempo o fluxo tentará realizar a gravação antes do tempo limite.Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out.

(Herdado de Stream)

Métodos

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

Começa uma leitura assíncrona.Begins an asynchronous read.

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

Inicia uma operação de leitura assíncrona.Begins an asynchronous read operation. (Considere o uso de ReadAsync(Byte[], Int32, Int32) em seu lugar.)(Consider using ReadAsync(Byte[], Int32, Int32) instead.)

(Herdado de Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

Começa uma gravação assíncrona.Begins an asynchronous write.

BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

Inicia uma operação de gravação assíncrona.Begins an asynchronous write operation. (Considere o uso de WriteAsync(Byte[], Int32, Int32) em seu lugar.)(Consider using WriteAsync(Byte[], Int32, Int32) instead.)

(Herdado de Stream)
Close()

Libera os recursos associados ao objeto IsolatedStorageFileStream.Releases resources associated with the IsolatedStorageFileStream object.

Close()

Fecha o fluxo atual e libera todos os recursos (como soquetes e identificadores de arquivos) associados ao fluxo atual.Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. Em vez de chamar esse método, verifique se o fluxo é descartado corretamente.Instead of calling this method, ensure that the stream is properly disposed.

(Herdado de Stream)
Close()

Fecha o fluxo atual e libera todos os recursos (como soquetes e identificadores de arquivos) associados ao fluxo atual.Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.

(Herdado de FileStream)
CopyTo(Stream)

Lê os bytes do fluxo atual e os grava em outro fluxo.Reads the bytes from the current stream and writes them to another stream.

(Herdado de Stream)
CopyTo(Stream, Int32)

Lê os bytes do fluxo atual e os grava em outro fluxo usando um tamanho do buffer especificado.Reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

(Herdado de Stream)
CopyToAsync(Stream)

Lê de forma assíncrona os bytes do fluxo atual e os grava em outro fluxo.Asynchronously reads the bytes from the current stream and writes them to another stream.

(Herdado de Stream)
CopyToAsync(Stream, CancellationToken)

Lê de forma assíncrona os bytes do fluxo atual e os grava em outro fluxo usando um token de cancelamento especificado.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token.

(Herdado de Stream)
CopyToAsync(Stream, Int32)

Lê de maneira assíncrona os bytes do fluxo atual e os grava em outro fluxo usando um tamanho do buffer especificado.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

(Herdado de Stream)
CopyToAsync(Stream, Int32, CancellationToken)

Lê de forma assíncrona os bytes do fluxo atual e os grava em outro fluxo usando um tamanho do buffer especificado e um token de cancelamento.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token.

(Herdado de Stream)
CopyToAsync(Stream, Int32, CancellationToken)

Lê de forma assíncrona os bytes do fluxo de arquivo atual e grava-os em outro fluxo usando um tamanho do buffer especificado e um token de cancelamento.Asynchronously reads the bytes from the current file stream and writes them to another stream, using a specified buffer size and cancellation token.

(Herdado de FileStream)
CreateObjRef(Type)

Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Herdado de MarshalByRefObject)
CreateWaitHandle()
Obsoleto.

Aloca um objeto WaitHandle.Allocates a WaitHandle object.

(Herdado de Stream)
Dispose()

Libera todos os recursos usados pelo Stream.Releases all resources used by the Stream.

(Herdado de Stream)
Dispose(Boolean)

Libera os recursos não gerenciados usados pelo IsolatedStorageFileStream e opcionalmente libera os recursos gerenciados.Releases the unmanaged resources used by the IsolatedStorageFileStream and optionally releases the managed resources.

DisposeAsync()

Libera de forma assíncrona os recursos não gerenciados usados pelo IsolatedStorageFileStream.Asynchronously releases the unmanaged resources used by the IsolatedStorageFileStream.

DisposeAsync()

Libera de forma assíncrona os recursos não gerenciados usados pelo Stream.Asynchronously releases the unmanaged resources used by the Stream.

(Herdado de Stream)
DisposeAsync()

Libera de forma assíncrona os recursos não gerenciados usados pelo FileStream.Asynchronously releases the unmanaged resources used by the FileStream.

(Herdado de FileStream)
EndRead(IAsyncResult)

Encerra uma solicitação de leitura assíncrona pendente.Ends a pending asynchronous read request.

EndRead(IAsyncResult)

Espera a leitura assíncrona pendente ser concluída.Waits for the pending asynchronous read to complete. (Considere o uso de ReadAsync(Byte[], Int32, Int32) em seu lugar.)(Consider using ReadAsync(Byte[], Int32, Int32) instead.)

(Herdado de Stream)
EndWrite(IAsyncResult)

Termina uma gravação assíncrona.Ends an asynchronous write.

EndWrite(IAsyncResult)

Encerra uma operação de gravação assíncrona.Ends an asynchronous write operation. (Considere o uso de WriteAsync(Byte[], Int32, Int32) em seu lugar.)(Consider using WriteAsync(Byte[], Int32, Int32) instead.)

(Herdado de Stream)
Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
Flush()

Limpa os buffers desse fluxo e faz com que todos os dados armazenados em buffer sejam gravados no arquivo.Clears buffers for this stream and causes any buffered data to be written to the file.

Flush(Boolean)

Limpa os buffers desse fluxo e faz com que os dados armazenados em buffer sejam gravados no arquivo e também limpa todos os buffers de arquivo intermediário.Clears buffers for this stream and causes any buffered data to be written to the file, and also clears all intermediate file buffers.

Flush(Boolean)

Limpa os buffers desse fluxo e faz com que os dados armazenados em buffer sejam gravados no arquivo e também limpa todos os buffers de arquivo intermediário.Clears buffers for this stream and causes any buffered data to be written to the file, and also clears all intermediate file buffers.

(Herdado de FileStream)
FlushAsync()

Limpa de forma assíncrona todos os buffers nesse fluxo e faz com que os dados armazenados em buffer sejam gravados no dispositivo subjacente.Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.

(Herdado de Stream)
FlushAsync(CancellationToken)

Limpa de forma assíncrona os buffers desse fluxo e faz com que todos os dados armazenados em buffer sejam gravados no arquivo.Asynchronously clears buffers for this stream and causes any buffered data to be written to the file.

FlushAsync(CancellationToken)

Limpa todos os buffers nesse fluxo de forma assíncrona, faz com que os dados armazenados em buffer sejam gravados no dispositivo subjacente e monitora as solicitações de cancelamento.Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.

(Herdado de FileStream)
GetAccessControl()

Obtém um objeto FileSecurity que encapsula as entradas de ACL (lista de controle de acesso) do arquivo descrito pelo objeto FileStream atual.Gets a FileSecurity object that encapsulates the access control list (ACL) entries for the file described by the current FileStream object.

(Herdado de FileStream)
GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetLifetimeService()

Recupera o objeto de serviço de tempo de vida atual que controla a política de ciclo de vida para esta instância.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Herdado de MarshalByRefObject)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
InitializeLifetimeService()

Obtém um objeto de serviço de tempo de vida para controlar a política de tempo de vida para essa instância.Obtains a lifetime service object to control the lifetime policy for this instance.

(Herdado de MarshalByRefObject)
Lock(Int64, Int64)

Impede que outros processos leiam ou gravem no fluxo.Prevents other processes from reading from or writing to the stream.

Lock(Int64, Int64)

Impede que outros processos façam a leitura ou gravação no FileStream.Prevents other processes from reading from or writing to the FileStream.

(Herdado de FileStream)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
MemberwiseClone(Boolean)

Cria uma cópia superficial do objeto MarshalByRefObject atual.Creates a shallow copy of the current MarshalByRefObject object.

(Herdado de MarshalByRefObject)
ObjectInvariant()
Obsoleto.

Oferece suporte a um Contract.Provides support for a Contract.

(Herdado de Stream)
Read(Byte[], Int32, Int32)

Copia bytes do objeto IsolatedStorageFileStream em buffer atual para uma matriz de bytes.Copies bytes from the current buffered IsolatedStorageFileStream object to a byte array.

Read(Span<Byte>)

Copia bytes do objeto IsolatedStorageFileStream em buffer atual para um intervalo de bytes.Copies bytes from the current buffered IsolatedStorageFileStream object to a byte span.

Read(Span<Byte>)

Quando for substituído em uma classe derivada, lê uma sequência de bytes do fluxo atual e avança a posição dentro do fluxo até o número de bytes lidos.When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

(Herdado de Stream)
Read(Span<Byte>)

Lê uma sequência de bytes do fluxo de arquivo atual e avança a posição no fluxo de arquivo até o número de bytes lidos.Reads a sequence of bytes from the current file stream and advances the position within the file stream by the number of bytes read.

(Herdado de FileStream)
ReadAsync(Byte[], Int32, Int32)

Lê uma sequência de bytes do fluxo atual de forma assíncrona e avança a posição no fluxo até o número de bytes lidos.Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

(Herdado de Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

Copia de forma assíncrona bytes do objeto IsolatedStorageFileStream em buffer atual para uma matriz de bytes.Asynchronously copies bytes from the current buffered IsolatedStorageFileStream object to a byte array.

ReadAsync(Byte[], Int32, Int32, CancellationToken)

Lê de forma assíncrona uma sequência de bytes do fluxo de arquivo atual, grava-os em uma matriz de bytes começando no deslocamento especificado, avança a posição no fluxo de arquivo até o número de bytes lidos e monitora as solicitações de cancelamento.Asynchronously reads a sequence of bytes from the current file stream and writes them to a byte array beginning at a specified offset, advances the position within the file stream by the number of bytes read, and monitors cancellation requests.

(Herdado de FileStream)
ReadAsync(Memory<Byte>, CancellationToken)

Copia de forma assíncrona bytes do objeto IsolatedStorageFileStream em buffer atual para um intervalo da memória de bytes.Asynchronously copies bytes from the current buffered IsolatedStorageFileStream object to a byte memory range.

ReadAsync(Memory<Byte>, CancellationToken)

Lê de forma assíncrona uma sequência de bytes do fluxo atual, avança a posição no fluxo até o número de bytes lidos e monitora as solicitações de cancelamento.Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

(Herdado de Stream)
ReadAsync(Memory<Byte>, CancellationToken)

Lê de forma assíncrona uma sequência de bytes do fluxo de arquivo atual e grava-os em uma região de memória, avança a posição no fluxo de arquivo até o número de bytes lidos e monitora as solicitações de cancelamento.Asynchronously reads a sequence of bytes from the current file stream and writes them to a memory region, advances the position within the file stream by the number of bytes read, and monitors cancellation requests.

(Herdado de FileStream)
ReadByte()

Lê um único byte do objeto IsolatedStorageFileStream no armazenamento isolado.Reads a single byte from the IsolatedStorageFileStream object in isolated storage.

Seek(Int64, SeekOrigin)

Define a posição atual desse objeto IsolatedStorageFileStream para o valor especificado.Sets the current position of this IsolatedStorageFileStream object to the specified value.

SetAccessControl(FileSecurity)

Aplica-se a entradas da ACL (lista de controle de acesso) descritas por um objeto FileSecurity para o arquivo descrito pelo objeto FileStream atual.Applies access control list (ACL) entries described by a FileSecurity object to the file described by the current FileStream object.

(Herdado de FileStream)
SetLength(Int64)

Define o comprimento desse objeto IsolatedStorageFileStream especificado value.Sets the length of this IsolatedStorageFileStream object to the specified value.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)
Unlock(Int64, Int64)

Permite que outros processos acessem todo ou parte de um arquivo que foi bloqueado anteriormente.Allows other processes to access all or part of a file that was previously locked.

Unlock(Int64, Int64)

Permite o acesso por outros processos a todo ou parte de um arquivo que foi bloqueado anteriormente.Allows access by other processes to all or part of a file that was previously locked.

(Herdado de FileStream)
Write(Byte[], Int32, Int32)

Grava um bloco de bytes no objeto de fluxo de arquivos de armazenamento isolado usando dados lidos de um buffer composto por uma matriz de bytes.Writes a block of bytes to the isolated storage file stream object using data read from a buffer consisting of a byte array.

Write(ReadOnlySpan<Byte>)

Grava um bloco de bytes no objeto de fluxo de arquivos de armazenamento isolado usando dados lidos de um buffer composto por um intervalo de bytes somente leitura.Writes a block of bytes to the isolated storage file stream object using data read from a buffer consisting of a read-only byte span.

Write(ReadOnlySpan<Byte>)

Quando for substituído em uma classe derivada, grava uma sequência de bytes no fluxo atual e avança a posição atual dentro desse fluxo até o número de bytes gravados.When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

(Herdado de Stream)
Write(ReadOnlySpan<Byte>)

Grava uma sequência de bytes de um intervalo somente leitura no fluxo de arquivo atual e avança a posição atual nesse fluxo de arquivo até o número de bytes gravados.Writes a sequence of bytes from a read-only span to the current file stream and advances the current position within this file stream by the number of bytes written.

(Herdado de FileStream)
WriteAsync(Byte[], Int32, Int32)

Grava assincronamente uma sequência de bytes no fluxo atual e avança a posição atual dentro desse fluxo no número de bytes gravados.Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

(Herdado de Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

Grava de forma assíncrona um bloco de bytes no objeto de fluxo de arquivos de armazenamento isolado usando dados lidos de um buffer composto uma matriz de bytes.Asynchronously writes a block of bytes to the isolated storage file stream object using data read from a buffer consisting of a byte array.

WriteAsync(Byte[], Int32, Int32, CancellationToken)

Grava uma sequência de bytes no fluxo atual assincronamente, avança a posição atual dentro desse fluxo pelo número de bytes gravados e monitora as solicitações de cancelamento.Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

(Herdado de FileStream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Grava de forma assíncrona um bloco de bytes no objeto de fluxo de arquivos de armazenamento isolado usando dados lidos de um buffer composto por um intervalo memória de bytes somente leitura.Asynchronously writes a block of bytes to the isolated storage file stream object using data read from a buffer consisting of a read-only byte memory range.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Grava uma sequência de bytes no fluxo atual assincronamente, avança a posição atual dentro desse fluxo pelo número de bytes gravados e monitora as solicitações de cancelamento.Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

(Herdado de Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Grava de forma assíncrona uma sequência de bytes de uma região de memória no fluxo de arquivo atual, avança a posição atual nesse fluxo de arquivo até o número de bytes gravados e monitora as solicitações de cancelamento.Asynchronously writes a sequence of bytes from a memory region to the current file stream, advances the current position within this file stream by the number of bytes written, and monitors cancellation requests.

(Herdado de FileStream)
WriteByte(Byte)

Grava um único byte para o objeto IsolatedStorageFileStream.Writes a single byte to the IsolatedStorageFileStream object.

Implantações explícitas de interface

IDisposable.Dispose()

Libera todos os recursos usados pelo Stream.Releases all resources used by the Stream.

(Herdado de Stream)

Métodos de Extensão

GetAccessControl(FileStream)

Retorna as informações de segurança de um arquivo.Returns the security information of a file.

SetAccessControl(FileStream, FileSecurity)

Altera os atributos de segurança de um arquivo existente.Changes the security attributes of an existing file.

AsInputStream(Stream)

Converte um fluxo gerenciado no .NET para Aplicativos da Windows Store em um fluxo de entrada no Windows Runtime.Converts a managed stream in the .NET for Windows Store apps to an input stream in the Windows Runtime.

AsOutputStream(Stream)

Converte um fluxo gerenciado no .NET para Aplicativos da Windows Store em um fluxo de saída no Windows Runtime.Converts a managed stream in the .NET for Windows Store apps to an output stream in the Windows Runtime.

AsRandomAccessStream(Stream)

Converte o fluxo especificado em um fluxo de acesso aleatório.Converts the specified stream to a random access stream.

ConfigureAwait(IAsyncDisposable, Boolean)

Configura como as esperas nas tarefas retornadas de um descartável assíncrono são realizadas.Configures how awaits on the tasks returned from an async disposable are performed.

Aplica-se a