I am working on memory mapped files. Is there any way to know the length of memory mapped file content? What I want is to append the existing memory mapped file. Its easy to append the bytes in the file but I am looking to append string.
We can check the CAPACITY property, but it returns the bytes size I think.
To be more clear, I am explaining the scenario. I am creating Memory mapped file A. I write "Hello" when I create it. It works fine. Now I want to write the "World" into existing file A.
I am using below code for this:
var file = MemoryMappedFile.OpenExisting("myFile");
string str = "String to append";
using (var view = file.CreateViewAccessor())
{
using (var stream = file.CreateViewStream())
{
System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
writer.Write(str.ToArray(), INT SIZE,Convert.ToInt32(view.Capacity), str.Length);//Error
}
}
using (var stream = file.CreateViewStream())
{
Console.WriteLine("Reading appended File");
System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);
Console.WriteLine(reader.ReadString());
Console.WriteLine(string.Empty);
}
I have marked the line with (//) that asks for the size. I want to know the value for (INT SIZE) Any help would be appreciated.
[EDIT] I am using C#, Visual Studio 2010.
Now I am using this code to append:
var file = MemoryMappedFile.OpenExisting("myFile");
string str = "String to append";
string str1 = string.Empty;
using (var stream = file.CreateViewStream())
{
System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);
str1 = reader.ReadString();
str1 = str1 + "\n" + str;
System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
writer.Write(str1);
}
using (var stream = file.CreateViewStream())
{
Console.WriteLine("Reading appended File");
System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);
Console.WriteLine(reader.ReadString());
Console.WriteLine(string.Empty);
}
But its not appending anything. Can you please check my code?