This is a C# Program to illustrate memory stream class.
This C# Program Illustrates Memory Stream Class.
Here the below program shows how to read and write data using memory as a backing store.
Here is source code of the C# Program to Illustrate Memory Stream Class. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
/* * C# Program to Illustrate Memory Stream Class */ using System; using System.IO; using System.Text; class MemStream { static void Main() { int count; byte[] byteArray; char[] charArray; UnicodeEncoding uniEncoding = new UnicodeEncoding(); byte[] firstString=uniEncoding.GetBytes("Invalid file path characters are: "); byte[] secondString = uniEncoding.GetBytes(Path.GetInvalidPathChars()); using(MemoryStream memStream = new MemoryStream(100)) { memStream.Write(firstString, 0 , firstString.Length); count = 0; while(count < secondString.Length) { memStream.WriteByte(secondString[count++]); } Console.WriteLine("Capacity = {0}, Length = {1}, Position = {2}\n", memStream.Capacity.ToString(), memStream.Length.ToString(), memStream.Position.ToString()); memStream.Seek(0, SeekOrigin.Begin); byteArray = new byte[memStream.Length]; count = memStream.Read(byteArray, 0, 20); while (count < memStream.Length) { byteArray[count++] = Convert.ToByte(memStream.ReadByte()); } charArray = new char[uniEncoding.GetCharCount(byteArray, 0, count)]; uniEncoding.GetDecoder().GetChars(byteArray, 0, count, charArray, 0); Console.WriteLine(charArray); Console.Read(); } } }
This C# program is used to illustrate memory stream class. The firstString variable is used to display the invalid file path characters and secondString variable is used to get an array containing the characters that are not allowed in path names using GetInvalidPathChars().
While loop is used to check the value of ‘count’ variable is less than the value of the length of ‘secondString’ variable. If the condition is true then execute the iteration of the loop. The WriteByte() function is used to write a byte to the current position in the file stream.
The memStream.Capacity.ToString() function is used to get or set the maximum number of characters contained in the memory allocated by the current instance. The memStream.Length.ToString() function is used to get the number of characters in the current string object.
The seek() function is used to specify the position in a stream to use for seeking. Program shows how to read and write data using memory as a backing store.
Capacity = 256 Length = 140 Position =140 Invalid File Path Characters are : "<>|
Sanfoundry Global Education & Learning Series – 1000 C# Programs.
- Apply for Computer Science Internship
- Check Computer Science Books
- Practice Computer Science MCQs
- Check C# Books
- Check MCA Books