IsolatedStorageFileStream Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Предоставляет файл в изолированном хранилище.
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
- Наследование
- Наследование
- Атрибуты
Примеры
В следующем консольном приложении показано, как использовать IsolatedStorageFile и IsolatedStorageFileStream записывать данные в файл изолированного хранилища. Пользователю предлагается войти в систему. Если пользователь является новым пользователем, URL-адрес новостей и URL-адрес спорта записываются в качестве личных настроек в изолированном хранилище. Если пользователь является возвращающим пользователем, отображаются текущие настройки пользователя. Примеры кода, используемые в этом пространстве имен, представлены в контексте этого примера приложения. Вы можете использовать программу Storeadm.exe (средство изолированного хранилища) для перечисления и удаления файлов изолированного хранилища, созданных с помощью этого консольного приложения.
// 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;
[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();
}
}
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
Комментарии
Используйте этот класс для чтения, записи и создания файлов в изолированном хранилище.
Так как этот класс расширяется FileStream, можно использовать экземпляр IsolatedStorageFileStream в большинстве ситуаций, когда FileStream может использоваться в противном случае, например для создания StreamReader или StreamWriter.
Этот тип реализует IDisposable интерфейс. Завершив использование типа, следует избавиться от него напрямую или косвенно. Чтобы удалить тип напрямую, вызовите его Dispose метод в блоке try/catch . Чтобы удалить его косвенно, используйте конструкцию языка, например using (в C#) или Using (в Visual Basic). Дополнительные сведения см. в разделе "Использование объекта, реализующего IDisposable" в IDisposable разделе интерфейса.
Important
Изолированное хранилище недоступно для приложений Магазина Windows 8.x. Вместо этого используйте классы данных приложений в пространствах имен Windows.Storage, включенных в API среды выполнения Windows для хранения локальных данных и файлов. Дополнительные сведения см. в разделе "Данные приложения " в Центре разработки для Windows.
Конструкторы
| Имя | Описание |
|---|---|
| IsolatedStorageFileStream(String, FileMode, FileAccess, FileShare, Int32, IsolatedStorageFile) |
Инициализирует новый экземпляр IsolatedStorageFileStream класса, предоставляющий доступ к файлу, указанному |
| IsolatedStorageFileStream(String, FileMode, FileAccess, FileShare, Int32) |
Инициализирует новый экземпляр IsolatedStorageFileStream класса, предоставляющий доступ к файлу, указанному |
| IsolatedStorageFileStream(String, FileMode, FileAccess, FileShare, IsolatedStorageFile) |
Инициализирует новый экземпляр IsolatedStorageFileStream класса, предоставляющий доступ к файлу, указанному |
| IsolatedStorageFileStream(String, FileMode, FileAccess, FileShare) |
Инициализирует новый экземпляр IsolatedStorageFileStream класса, предоставляющий доступ к файлу, указанному |
| IsolatedStorageFileStream(String, FileMode, FileAccess, IsolatedStorageFile) |
Инициализирует новый экземпляр IsolatedStorageFileStream класса, предоставляющий доступ к файлу, указанному |
| IsolatedStorageFileStream(String, FileMode, FileAccess) |
Инициализирует новый экземпляр IsolatedStorageFileStream класса, предоставляющий доступ к файлу, указанному |
| IsolatedStorageFileStream(String, FileMode, IsolatedStorageFile) |
Инициализирует новый экземпляр IsolatedStorageFileStream класса, предоставляющий доступ к файлу, указанному |
| IsolatedStorageFileStream(String, FileMode) |
Инициализирует новый экземпляр IsolatedStorageFileStream объекта, предоставляющий доступ к файлу, указанному |
Свойства
| Имя | Описание |
|---|---|
| CanRead |
Возвращает логическое значение, указывающее, можно ли читать файл. |
| CanSeek |
Возвращает логическое значение, указывающее, поддерживаются ли операции поиска. |
| CanTimeout |
Возвращает значение, определяющее, может ли текущий поток истекает время ожидания. (Унаследовано от Stream) |
| CanWrite |
Возвращает логическое значение, указывающее, можно ли записывать в файл. |
| Handle |
Устаревшие..
Устаревшие..
Устаревшие..
Возвращает дескриптор файла, который инкапсулирует текущий IsolatedStorageFileStream объект. Доступ к этому свойству не разрешен для IsolatedStorageFileStream объекта и вызывает исключение IsolatedStorageException. |
| IsAsync |
Возвращает логическое значение, указывающее, был ли IsolatedStorageFileStream объект открыт асинхронно или синхронно. |
| Length |
Возвращает длину IsolatedStorageFileStream объекта. |
| Name |
Возвращает абсолютный путь к файлу, открываемого в файле |
| Position |
Возвращает или задает текущую позицию текущего IsolatedStorageFileStream объекта. |
| ReadTimeout |
Возвращает или задает значение в миллисекундах, которое определяет, сколько времени поток попытается прочитать до истечения времени ожидания. (Унаследовано от Stream) |
| SafeFileHandle |
SafeFileHandle Возвращает объект, представляющий дескриптор файла операционной системы для файла, который инкапсулирует текущий IsolatedStorageFileStream объект. |
| WriteTimeout |
Возвращает или задает значение в миллисекундах, определяющее, сколько времени поток попытается записать до истечения времени ожидания. (Унаследовано от Stream) |
Методы
| Имя | Описание |
|---|---|
| BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) |
Начинает асинхронное чтение. |
| BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) |
Начинает асинхронную запись. |
| Close() |
Освобождает ресурсы, связанные с IsolatedStorageFileStream объектом. |
| CopyTo(Stream, Int32) |
Считывает байты из текущего потока и записывает их в другой поток, используя указанный размер буфера. Обе позиции потоков расширены по количеству скопированных байтов. (Унаследовано от Stream) |
| CopyTo(Stream, Int32) |
Считывает байты из текущего потока и записывает их в другой поток, используя указанный размер буфера. Обе позиции потоков расширены по количеству скопированных байтов. (Унаследовано от FileStream) |
| CopyTo(Stream) |
Считывает байты из текущего потока и записывает их в другой поток. Обе позиции потоков расширены по количеству скопированных байтов. (Унаследовано от Stream) |
| CopyToAsync(Stream, CancellationToken) |
Асинхронно считывает байты из текущего потока и записывает их в другой поток с помощью указанного маркера отмены. Обе позиции потоков расширены по количеству скопированных байтов. (Унаследовано от Stream) |
| CopyToAsync(Stream, Int32, CancellationToken) |
Асинхронно считывает байты из текущего потока и записывает их в другой поток, используя указанный размер буфера и маркер отмены. Обе позиции потоков расширены по количеству скопированных байтов. (Унаследовано от Stream) |
| CopyToAsync(Stream, Int32, CancellationToken) |
Асинхронно считывает байты из текущего файлового потока и записывает их в другой поток, используя указанный размер буфера и маркер отмены. (Унаследовано от FileStream) |
| CopyToAsync(Stream, Int32) |
Асинхронно считывает байты из текущего потока и записывает их в другой поток, используя указанный размер буфера. Обе позиции потоков расширены по количеству скопированных байтов. (Унаследовано от Stream) |
| CopyToAsync(Stream) |
Асинхронно считывает байты из текущего потока и записывает их в другой поток. Обе позиции потоков расширены по количеству скопированных байтов. (Унаследовано от Stream) |
| CreateObjRef(Type) |
Создает объект, содержащий все соответствующие сведения, необходимые для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. (Унаследовано от MarshalByRefObject) |
| CreateWaitHandle() |
Устаревшие..
Устаревшие..
Устаревшие..
Выделяет объект WaitHandle. (Унаследовано от Stream) |
| Dispose() |
Освобождает все ресурсы, используемые параметром Stream. (Унаследовано от Stream) |
| Dispose(Boolean) |
Освобождает неуправляемые ресурсы, используемые IsolatedStorageFileStream и при необходимости освобождает управляемые ресурсы. |
| DisposeAsync() |
Асинхронно освобождает неуправляемые ресурсы, используемые IsolatedStorageFileStreamв . |
| EndRead(IAsyncResult) |
Завершает ожидающий асинхронный запрос на чтение. |
| EndWrite(IAsyncResult) |
Заканчивает асинхронную запись. |
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| Flush() |
Очищает буферы для этого потока и приводит к записи в файл любых буферных данных. |
| Flush(Boolean) |
Очищает буферы для этого потока и приводит к записи в файл любых буферных данных, а также очищает все промежуточные буферы файлов. |
| FlushAsync() |
Асинхронно очищает все буферы для этого потока и приводит к записи всех буферных данных на базовое устройство. (Унаследовано от Stream) |
| FlushAsync(CancellationToken) |
Асинхронно очищает буферы для этого потока и приводит к записи в файл любых буферных данных. |
| FlushAsync(CancellationToken) |
Асинхронно очищает все буферы для этого потока, приводит к записи буферных данных в файл и отслеживает запросы на отмену. (Унаследовано от FileStream) |
| GetAccessControl() |
FileSecurity Возвращает объект, инкапсулирующий записи списка управления доступом (ACL) для файла, описанного текущим FileStream объектом. (Унаследовано от FileStream) |
| GetHashCode() |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
| GetLifetimeService() |
Устаревшие..
Извлекает текущий объект службы времени существования, который управляет политикой времени существования для этого экземпляра. (Унаследовано от MarshalByRefObject) |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| InitializeLifetimeService() |
Устаревшие..
Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. (Унаследовано от MarshalByRefObject) |
| Lock(Int64, Int64) |
Запрещает другим процессам чтение или запись в поток. |
| Lock(Int64, Int64) |
Запрещает другим процессам чтение или запись в нее FileStream. (Унаследовано от FileStream) |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| MemberwiseClone(Boolean) |
Создает неглубокую копию текущего MarshalByRefObject объекта. (Унаследовано от MarshalByRefObject) |
| ObjectInvariant() |
Устаревшие..
Предоставляет поддержку Contract. (Унаследовано от Stream) |
| Read(Byte[], Int32, Int32) |
Копирует байты из текущего буферизованного IsolatedStorageFileStream объекта в массив байтов. |
| Read(Span<Byte>) |
Копирует байты из текущего буферизованного IsolatedStorageFileStream объекта в диапазон байтов. |
| ReadAsync(Byte[], Int32, Int32, CancellationToken) |
Асинхронно копирует байты из текущего буферизованного IsolatedStorageFileStream объекта в массив байтов. |
| ReadAsync(Byte[], Int32, Int32, CancellationToken) |
Асинхронно считывает последовательность байтов из текущего потока файлов и записывает их в массив байтов, начиная с указанного смещения, перемещает позицию в потоке файлов по количеству байтов, считываемых и отслеживает запросы на отмену. (Унаследовано от FileStream) |
| ReadAsync(Byte[], Int32, Int32) |
Асинхронно считывает последовательность байтов из текущего потока и перемещает позицию в потоке по числу байтов. (Унаследовано от Stream) |
| ReadAsync(Memory<Byte>, CancellationToken) |
Асинхронно копирует байты из текущего буферизованного IsolatedStorageFileStream объекта в диапазон памяти байтов. |
| ReadAtLeast(Span<Byte>, Int32, Boolean) |
Считывает по крайней мере минимальное количество байтов из текущего потока и перемещает положение в потоке по количеству байтов, считываемых. (Унаследовано от Stream) |
| ReadAtLeastAsync(Memory<Byte>, Int32, Boolean, CancellationToken) |
Асинхронно считывает по крайней мере минимальное количество байтов из текущего потока, перемещает положение в потоке по количеству операций чтения байтов и отслеживает запросы на отмену. (Унаследовано от Stream) |
| ReadByte() |
Считывает один байт из IsolatedStorageFileStream объекта в изолированном хранилище. |
| ReadExactly(Byte[], Int32, Int32) |
Считывает количество байтов из текущего потока и перемещает |
| ReadExactly(Span<Byte>) |
Считывает байты из текущего потока и перемещает положение в потоке, пока не будет заполнено |
| ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken) |
Асинхронно считывает количество байтов из текущего потока, перемещает |
| ReadExactlyAsync(Memory<Byte>, CancellationToken) |
Асинхронно считывает байты из текущего потока, перемещает положение в потоке до тех пор, пока не |
| Seek(Int64, SeekOrigin) |
Задает текущее положение этого IsolatedStorageFileStream объекта указанным значением. |
| SetAccessControl(FileSecurity) |
Применяет записи списка управления доступом (ACL), описанные объектом, к файлу, описанному FileSecurity текущим FileStream объектом. (Унаследовано от FileStream) |
| SetLength(Int64) |
Задает длину этого IsolatedStorageFileStream объекта указанным |
| ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |
| Unlock(Int64, Int64) |
Позволяет другим процессам получить доступ ко всем или части файла, который ранее был заблокирован. |
| Unlock(Int64, Int64) |
Разрешает доступ другим процессам ко всем или части файла, который ранее был заблокирован. (Унаследовано от FileStream) |
| Write(Byte[], Int32, Int32) |
Записывает блок байтов в изолированный объект потока файлов хранилища с помощью данных, считываемых из буфера, состоящего из массива байтов. |
| Write(ReadOnlySpan<Byte>) |
Записывает блок байтов в изолированный объект потока файлов хранилища с помощью данных, считываемых из буфера, состоящего из диапазона байтов только для чтения. |
| WriteAsync(Byte[], Int32, Int32, CancellationToken) |
Асинхронно записывает блок байтов в объект изолированного потока файлов хранилища с помощью данных, считываемых из буфера, состоящего из массива байтов. |
| WriteAsync(Byte[], Int32, Int32, CancellationToken) |
Асинхронно записывает последовательность байтов в текущий поток, перемещает текущую позицию в этом потоке по количеству записанных байтов и отслеживает запросы на отмену. (Унаследовано от FileStream) |
| WriteAsync(Byte[], Int32, Int32) |
Асинхронно записывает последовательность байтов в текущий поток и перемещает текущую позицию в этом потоке по количеству записанных байтов. (Унаследовано от Stream) |
| WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) |
Асинхронно записывает блок байтов в объект изолированного потока файлов хранилища с помощью данных, считываемых из буфера, состоящего из диапазона памяти только для чтения. |
| WriteByte(Byte) |
Записывает один байт в IsolatedStorageFileStream объект. |
Явные реализации интерфейса
| Имя | Описание |
|---|---|
| IDisposable.Dispose() |
Освобождает все ресурсы, используемые параметром Stream. (Унаследовано от Stream) |
Методы расширения
| Имя | Описание |
|---|---|
| AsInputStream(Stream) |
Преобразует управляемый поток в .NET для приложений Магазина Windows в входной поток в среде выполнения Windows. |
| AsOutputStream(Stream) |
Преобразует управляемый поток в .NET для приложений Магазина Windows в выходной поток в среде выполнения Windows. |
| AsRandomAccessStream(Stream) |
Преобразует указанный поток в поток случайного доступа. |
| ConfigureAwait(IAsyncDisposable, Boolean) |
Настраивает способ ожидания задач, возвращаемых из асинхронного удаления. |
| CopyToAsync(Stream, PipeWriter, CancellationToken) |
Асинхронно считывает байты из Stream указанных и записывает их в указанный PipeWriterмаркер отмены. |
| GetAccessControl(FileStream) |
Возвращает сведения о безопасности файла. |
| SetAccessControl(FileStream, FileSecurity) |
Изменяет атрибуты безопасности существующего файла. |