Search code examples
c#arraystoarray

ToArray() function limitation


I am using the .ToArray() method to convert my string to char array whose size i have kept char[] buffer = new char[1000000]; but when I am using the following code:

using (StreamReader streamReader = new StreamReader(path1))
{
    buffer = streamReader.ReadToEnd().ToCharArray();
}
// buffer = result.ToArray();
threadfunc(data_path1);

The size of the buffer getting fixed up to 8190, even it is not reading the whole file after using .ToCharArray() or .ToArray(). What is the reason for this does .ToCharArray() or .ToArray() have size limitations? As if I do not use this function I'm able to read whole file in string format, but when trying to convert it into char array by using this function I am getting size limitations.


Solution

  • ToCharArray() returns new instance of of array. So your buffer will refer to the new instance which is the size of data returned by ReadToEnd.

    If you want keep buffer same size just add new array to the existed one

    char[] buffer = new char[1000000];
    using (StreamReader streamReader = new StreamReader(path1))
    {
        var tempArray = streamReader.ReadToEnd().ToCharArray();
        tempArray.CopyTo(buffer, 0);
    }
    

    If you want just use the result array - you don't need to "predict" the size of array - just use returned one

    public char[] GetArrayFromFile(string pathToFile)
    {
        using (StreamReader streamReader = new StreamReader(path1))
        {
            var data = streamReader.ReadToEnd();
        }
        return data.ToCharArray();
    }    
    
    var arrayFromFile = GetArrayFromFile(@"..\path.file");