База ответов ИНТУИТ

Практикум прикладного программирования на C# в среде VS.NET 2008

<<- Назад к вопросам

Следующий код:Imports SystemImports System.IOModule VBDemo Sub Main() Dim Bytes() As Byte = New Byte(10) {} Dim I As Integer Dim MemStr As New MemoryStream()Dim FileStr As New FileStream(“c:\temp\bytes.bin”, _ FileMode.CreateNew) Dim Rand As System.Random = New System.Random() For I = 0 To 9 Bytes(I) = Rand.Next(0, 100) Next MemStr.Write(Bytes, 0, I) MemStr.WriteTo(FileStr) MemStr.Close() FileStr.Close() End SubEnd Moduleдемонстрирует:

(Ответ считается верным, если отмечены все правильные варианты ответов.)

Варианты ответа
использование класса MemoryStream для сохранения потока в файле (Верный ответ)
использование класса MemoryStream для задания содержимого потока(Верный ответ)
использование класса MemoryStream для создания нового потока в памяти(Верный ответ)
Похожие вопросы
Следующий пример:
Imports SystemImports System.IOModule VBDemoSub Main()    Dim Bytes As Byte()    Dim I As Integer    Dim Reader As BinaryReader    Reader = New BinaryReader(File.OpenRead (“c:\demo.exe”))    While Reader.PeekChar() > -1        Bytes = Reader.ReadBytes(16)        For I = 0 To Bytes.GetUpperBound(0)            Console.Write(“0x{0:X2}|”, Bytes(I))        Next        Console.WriteLine()    End WhileEnd SubEnd Module 
показывает:
Следующий пример:
Imports SystemImports System.IOModule VBDemoSub Main()    Dim Bytes As Byte()    Dim Reader As BinaryReader    Dim Writer As BinaryWriter    Reader = New BinaryReader(File.OpenRead (“c:\demo.exe”))    Writer = New BinaryWriter(File.Create (“c:\demo_copy.exe”))    While Reader.PeekChar() > -1        Bytes = Reader.ReadBytes(1024)        Writer.Write(Bytes)    End While    Reader.Close()    Writer.Flush()    Writer.Close()End SubEnd Module
демонстрирует:
Фрагмент кода:
Imports System Imports System.IO Imports System.Security.Cryptography Module VBDemo Sub Main()     Dim Bytes() As Byte = {65, 66, 67, 68, 69, 70, 71, 72, 73, 74}     Dim EncBytes() As Byte = New Byte(15) {}     Dim DecBytes() As Byte = New Byte(10) {}     Dim FileName As String = "c:\temp\text.enc"     Dim EncFile As New FileStream(FileName, FileMode.Create, _         FileAccess.Write)     Dim DES As New DESCryptoServiceProvider()     Dim DESEncrypt As ICryptoTransform = DES.CreateEncryptor()     Dim CryptoStreamEnc As New CryptoStream(EncFile, DESEncrypt, _         CryptoStreamMode.Write)     Console.WriteLine("Original Data")     ToHexArray(Bytes)     CryptoStreamEnc.Write(Bytes, 0, Bytes.Length)     CryptoStreamEnc.Close()     EncFile.Close()     EncFile = New FileStream(FileName, FileMode.Open, FileAccess.Read)     EncFile.Read(EncBytes, 0, EncFile.Length)     EncFile.Close()     Console.WriteLine("Encrypted Data")     ToHexArray(EncBytes)     Console.WriteLine()     Dim DecFile As New FileStream(FileName, FileMode.Open, _         FileAccess.Read)     Dim DESDecrypt As ICryptoTransform = DES.CreateDecryptor()     Dim CryptoStreamDec As New CryptoStream(DecFile, DESDecrypt, _         CryptoStreamMode.Read)     Dim Reader As New BinaryReader(CryptoStreamDec)     Console.WriteLine("Decrypted Data")     DecBytes = Reader.ReadBytes(10)     ToHexArray(DecBytes) End Sub Sub ToHexArray(ByVal A As Byte())     Dim I As Integer     For I = 0 To A.GetUpperBound(0)         Console.Write("0x{0:x2} ", A(I))         If I = 7 Then             Console.WriteLine()         End If     Next End Sub End Module
показано:
Следующий пример:
Imports SystemImports System.IOModule VBDemoSub Main()    Dim FileName As String = _         “C:\Program Files\Microsoft.NET\FrameworkSDK\include\corsym.h”    Dim Reader As TextReader    Dim I As Int32    Reader = New StreamReader(FileName)    While Reader.Peek() > -1        Console.WriteLine(Reader.ReadLine)        I += 1    End While    Console.WriteLine(“Read {0:G} lines”, I)    Reader.Close()End SubEnd Module
показано:
Внесем в файл C:\a.txt числа 0123456789, выполним следующий код:
private void button1_Click(object sender, System.EventArgs e){//Файл создан заранее его объем должен быть достаточно большим string path = "C:\a.txt";FileInfo fileinfo=new FileInfo(path);  using(FileStream       fileStream = fileinfo.OpenWrite()) {  fileStream.Seek(0, SeekOrigin.Begin);          byte[] bArray=new byte[10];  Random numrandom = new Random();  for(int i=0; i <bArray.Length; i++)  {   //Записываем случайные числа в массив   bArray[i]=(byte)numrandom.Next(48,57);   fileStream.WriteByte(bArray[i]);   textBox1.Text+=bArray[i];  }				 }}
полный результат выполнения кода:
Пример кода:
Imports SystemImports System.IOModule VBDemoSub Main()Dim FileName As String = "c:\temp\mytext01.txt"Dim Writer As StreamWriterDim MyFile As New FileInfo(FileName)Writer = MyFile.CreateText()Writer.WriteLine("Created by"&MyFile.GetType.ToString)Writer.WriteLine("Written by"&Writer.ToString)Writer.Close()End Sub
демонстрирует:
Пример кода:
Imports SystemImports System.IOModule VBDemoSub Main()Dim Path As String = "c:\"Dim DirInfo As New DirectoryInfo(Path)Dim Dirs() As DirectoryInfoDim I As IntegerConsole.WriteLine("Initial Directory:"&DirInfo.FullName);Dirs=DirInfo.GetDirectoriesFor I=0 To Dirs.GetUpperBound(0)Console.WriteLine(Dirs(I).FullName)NextEnd SubEnd Module
демонстрирует:
Внесем в файл C:\a.txt числа 0123456789, выполним следующий код:
private void button1_Click(object sender, System.EventArgs e){   //Файл создан заранее его объем должен быть достаточно большимstring path = "C:\a.txt"; FileInfo fileinfo=new FileInfo(path);  using(FileStream   fileStream = fileinfo.OpenRead()) {  fileStream.Seek(0, SeekOrigin.Begin);  byte[] bArray=new byte[10];    int iBytes=fileStream.Read(bArray,0,10);    if(iBytes == 10)  {   for(int i=0; i < iBytes; i++)   textBox1.Text+= bArray[i];  }}						
Результат:
Рассмотрим пример кода:struct Situation { //Наш поток public FileStream filestream; //Здесь будем хранить данные public byte [] bText; //Размер буфера public long bufSize;public MaualResetEvent manualresetevent;}static void EndAsingRead(IAsyncResult iasyncresult){Situation situation = (Situation)iasyncresult.AsyncState; int readCount = situation.filestream.EndRead(iasyncresult); situation.filestream.Close();situation.manualresetevent.Set(); situation.manualresetevent.Close();}Если в приведенном выше коде закоментировать строку situation.manualresetevent.Set(), то в этом случае:
Пример кода:
Imports SystemImports System.IOModule VBDemoSub Main()Dim Path As String = GetPersonalFolder()&"\MyText"Dim DirInfo As New DirectoryInfo(Path)Dim Parent As StringConsole.WriteLine("Initial Directory : "&DirInfo.FullName)Parent = DirInfo.Parent.FullNameWhile Parent DirInfo.Root.FullNameConsole.WriteLine("Parent Directory : " & _DirInfo.Parent.FullName)Parent = DirInfo.Parent.FullNameDirInfo = New DirectoryInfo(Parent)End WhileEnd SubFunction GetPersonalFolder() As StringDim E As EnvironmentReturn E.GetFolderPath(Environment.SpecialFolder.Personal)End FunctionEnd Module
демонстрирует: