Note: If you want to experience a complete C++ .NET/C++-CLI programming tutorial please jump to Visual C++ .NET programming tutorial.
Create a new CLR console application project and you might want to use FileStreamCplus as the project and solution names.
Add the following code.
// FileStreamCplus.cpp : main project file.
#include "stdafx.h"
using namespace System; using namespace System::IO;
int main(array<System::String ^> ^args) { FileStream^ MyFileStream = nullptr; try { MyFileStream = gcnew FileStream("C:\\John.dat", FileMode::Create, FileAccess::ReadWrite); Console::WriteLine("John.dat successfully created, check the C:\\!"); } catch (Exception^ e) { Console::WriteLine("Failed to create file with the following error: " + e->Message); } finally { MyFileStream->Close(); } return 0; } |
Build and run the project.
The following is the output example when run at the Windows console/command prompt.
Create a new console application project. You can use the solution and project name as shown in the following Figure.
Add the following codes.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO;
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { FileStream MyFileStream = null; try { MyFileStream = new FileStream(".\\Jim.dat", FileMode.Create, FileAccess.ReadWrite); Console.WriteLine("Jim.dat successfully created, check the local folder!"); } catch (Exception e) { Console.WriteLine("Failed to create file with the following error: " + e.Message); } finally { MyFileStream.Close(); } } } } |
An output sample:
Create a new console application project and you can use the solution and project names as shown in the following Figure.
|
|
Add the following codes.
Imports System.IO
Module Module1
Sub Main() Dim MyFileStream As FileStream MyFileStream = Nothing
Try 'Open the file MyFileStream = New FileStream(".\Jim.doc", FileMode.Create, FileAccess.ReadWrite) 'Write some prompt Console.WriteLine("Jim.doc file successfully created under the current folder!") Catch e As Exception ' If failed Console.WriteLine("Failed to create/open file stream with error: " + e.Message) Finally 'Close stream MyFileStream.Close() End Try End Sub End Module |
An output sample:
It’s important to note that many other prototypes for the FileStream constructor enable more control for gaining access to a file. Two main parameters featured in each prototype control file creation: FileMode and FileAccess. FileMode is an enumeration that determines how a file is created. For our sample code, we use the Create enumeration flag that causes the system to create a new file if one does not already exist; otherwise, the flag overwrites an existing file. The other enumeration, FileAccess, determines if your application can read or write to the file. For our sample code, we’ve decided to do both.
Create a new CLR console application project and you might want to use FileStreamSampleCP as the project and solution names.
Add the following code.
// FileStreamSampleCP.cpp : main project file.
#include "stdafx.h"
using namespace System; using namespace System::IO;
[STAThread] int main(array<System::String ^> ^args) { // To work with files requires either creating a new file or opening an // existing file. There is a convenient class named File in the System.IO // namespace that will allow you to open a file. For this sample we will // create a file named Jim in the current working directory. FileStream^ MyFileStream = nullptr;
try { try { String^ FileName = "setan.dat"; // "C:\\temp" MyFileStream = gcnew FileStream(FileName, FileMode::Create, FileAccess::ReadWrite); Console::WriteLine("{0} file created successfully", FileName); } catch (Exception^ e) { throw gcnew Exception("Failed to create/open filestream with error: " + e->Message); }
// Alternately we could have opened or created the same file stream using // the static class File in the System.IO namespace. For example: // MyFileStream = File::Open(FileName, FileMode::Create, FileAccess::ReadWrite);
// Let's write 10 bytes to our new file using the stream. For simplicity // we will write an array of 10 bytes where each byte contains a numeric value 0 - 9. array< Byte >^ MyByteArray = gcnew array< Byte >(10);
for (short i = 0; i < MyByteArray->Length; i++) { MyByteArray[i] = (Byte)i; }
try { MyFileStream->Write(MyByteArray, 0, MyByteArray->Length); Console::WriteLine("Write() is OK"); } catch (Exception^ e) { throw gcnew Exception("Write failed with error: " + e->Message); }
// Now let's prepare to read the bytes that we have just written. To // do so requires seeking back to the beginning of the file and reading the bytes. try { MyFileStream->Seek(0, SeekOrigin::Begin); Console::WriteLine("Seek() is OK"); } catch (Exception^ e) { throw gcnew Exception("Seek failed with error: " + e->Message); }
// Now we may begin reading the bytes that were originally written. For // simplicity reasons we decided to read one byte at a time and print each byte to the console. array< Byte >^ MyReadBuffer = gcnew array< Byte >(1);
while (true) { int BytesRead;
try { BytesRead = MyFileStream->Read(MyReadBuffer, 0, MyReadBuffer->Length); Console::WriteLine("Read() is OK"); } catch (Exception^ e) { throw gcnew Exception("Read failed with error: " + e->Message); }
if (BytesRead == 0) { Console::WriteLine("No more bytes to read"); break; }
Console::WriteLine("Read byte -> " + MyReadBuffer[0].ToString()); } } catch (Exception^ e) { Console::WriteLine("Found error " + e->Message); } finally { // We are finished performing IO on the file. We need to close the file // to release operating system resources related to the file. MyFileStream->Close(); Console::WriteLine("Close() is OK"); } return 0; } |
Build and run the project.
The following is the output example when run at the Windows console/command prompt.
Create a new console application project. You can use the solution and project name as shown in the following Figure.
Add the following code.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO;
// <summary> // FileStreamSampleCS is a very simple sample demonstrating how to create a new file, // write bytes to the file, and read bytes from the file. // </summary> namespace FileStreamSampleCS { class Program { // <summary> // The main entry point for the application. // </summary> [STAThread] static void Main(string[] args) { // To work with files requires either creating a new file or opening an // existing file. There is a convenient class named File in the System.IO // namespace that will allow you to open a file. For this sample we will // create a file named Jim in the current working directory. FileStream MyFileStream = null;
try { try { MyFileStream = new FileStream(".\\Jim.dat", FileMode.Create, FileAccess.ReadWrite); Console.WriteLine("Jim.dat file created successfully"); } catch (Exception e) { throw new Exception("Failed to create/open filestream with error: " + e.Message); }
// Alternately we could have opened or created the same file stream using // the static class File in the System.IO namespace. For example: // MyFileStream = File.Open(".\\Jim.dat", FileMode.Create, FileAccess.ReadWrite);
catch (Exception e) { throw new Exception("Read failed with error: " + e.Message); }
if (BytesRead == 0) { Console.WriteLine("No more bytes to read"); break; } Console.WriteLine("Read byte -> " + MyReadBuffer[0].ToString()); } } catch (Exception e) { Console.WriteLine(e.Message); } finally { // We are finished performing IO on the file. We need to close the file // to release operating system resources related to the file. MyFileStream.Close(); Console.WriteLine("Close() is OK"); } } } } |
An output sample:
Create a new console application project. You can use the solution and project name as shown in the following Figure.
Add the following code.
Imports System Imports System.IO
'FileStreamSampleVB is a very simple sample demonstrating how to create a new file, 'write bytes to the file, and read bytes from the file. Module Module1 'The main entry point for the application. Sub Main() ' To work with files requires either creating a new file or opening an ' existing file. There is a convenient class named File in the System.IO ' namespace that will allow you to open a file. For this sample we will ' create a file named Jim.dat in the current working directory.
'Declare a file stream object Dim MyFileStream As FileStream = Nothing
Try Try 'Open the file MyFileStream = New FileStream(".\Jim.dat", FileMode.Create, FileAccess.ReadWrite) Console.WriteLine("Jim.dat successfully created/opened under current folder!") Catch e As Exception Throw New Exception("Failed to create/open filestream with error: " + e.Message) End Try
' Alternately we could have opened or created the same file stream using ' the static class File in the System.IO namespace. For example: ' MyFileStream = File.Open(".\Jim.dat", FileMode.Create, FileAccess.ReadWrite)
' Let's write 10 bytes to our new file using the stream. For simplicity ' we will write an array of 10 bytes where each byte contains a numeric value 0 - 9. Dim MyByteArray(10) As Byte Dim i As Short
For i = MyByteArray.GetLowerBound(0) To MyByteArray.GetUpperBound(0) - 1 MyByteArray(i) = i Next
Try MyFileStream.Write(MyByteArray, 0, MyByteArray.GetUpperBound(0)) Console.WriteLine("Write() is OK!")
Catch e As Exception Throw New Exception("Write failed with error: " + e.Message) End Try
' Now let's prepare to read the bytes that we have just written. To ' do so requires seeking back to the beginning of the file and reading the bytes. Try MyFileStream.Seek(0, SeekOrigin.Begin) Console.WriteLine("Seek() is OK") Catch e As Exception Throw New Exception("Seek failed with error: " + e.Message) End Try
' Now we may begin reading the bytes that were originally written. For ' simplicity reasons we decided to read one byte at a time and print each byte to the console. Dim MyReadBuffer(1) As Byte
While True Dim BytesRead As Integer Try BytesRead = MyFileStream.Read(MyReadBuffer, 0, MyReadBuffer.GetUpperBound(0)) Console.WriteLine("Read() is OK") Catch e As Exception Throw New Exception("Read failed with error: " + e.Message) End Try If BytesRead = 0 Then Console.WriteLine("No more bytes to read!") Exit While End If Console.WriteLine("Read byte -> " + MyReadBuffer(0).ToString()) End While Catch e As Exception Console.WriteLine(e.Message) Finally ' We are finished performing IO on the file. We need to close the file ' to release operating system resources related to the file. MyFileStream.Close() Console.WriteLine("Close is OK") End Try End Sub End Module |
An output sample: