File to string

I'm trying to read a file into memory for further processing. I can not achieve this by using the SyncFusion File Upload component, even though the Blazor InputFile works as expected.

Here is the code I used:

<div class="container-lg">
    <div class="row">
        <div class="col">
            <p>Working</p>
            <InputFile OnChange="@LoadFiles" multiple />
        </div>
    </div>
    <div class="row">
        <div class="col">
            <p>Not working</p>
            <SfUploader ID="UploadFiles" AllowedExtensions=".ini" MaxFileSize=50000 AllowMultiple="false" AutoUpload="false" >
                <UploaderEvents ValueChange="LoadFilesSf" />
            </SfUploader>
        </div>
    </div>
</div>




@code {
    public async void LoadFiles(InputFileChangeEventArgs e)
    {
        Console.WriteLine("Upload triggered");
        var browserFile = e.File;
        var reader = await new StreamReader(browserFile.OpenReadStream()).ReadToEndAsync();
        Console.WriteLine(reader);
    }


    public async void LoadFilesSf(UploadChangeEventArgs args)
    {
        Console.WriteLine("Upload triggered");
        if(args.Files.Count == 1)
        {
            var file = args.Files[0];
            var reader = await new StreamReader(file.Stream).ReadToEndAsync();
            Console.WriteLine(reader);
        }
    }
}


How can I read the uploaded file content into a string?


1 Reply

SP Sureshkumar P Syncfusion Team February 28, 2022 05:05 AM UTC

HI Henning, 
 
We suggest you set the stream position at 0 to achieve your requirement.  
 
Find the modified code example: 
 
<div class="container-lg"> 
    <div class="row"> 
        <div class="col"> 
            <p>Working</p> 
            <InputFile OnChange="@LoadFiles" multiple /> 
        </div> 
    </div> 
    <div class="row"> 
        <div class="col"> 
            <p>Not working</p> 
            <SfUploader ID="UploadFiles" AllowedExtensions=".ini" MaxFileSize=50000 AllowMultiple="false" AutoUpload="false" > 
                <UploaderEvents ValueChange="LoadFilesSf" /> 
            </SfUploader> 
        </div> 
    </div> 
</div> 
 
 
 
 
@code { 
    public async void LoadFiles(InputFileChangeEventArgs e) 
    { 
        Console.WriteLine("Upload triggered"); 
        var browserFile = e.File; 
        var reader = await new StreamReader(browserFile.OpenReadStream()).ReadToEndAsync(); 
        Console.WriteLine(reader); 
    } 
 
 
    public async void LoadFilesSf(UploadChangeEventArgs args) 
    { 
        Console.WriteLine("Upload triggered"); 
        if(args.Files.Count == 1) 
        { 
            var file = args.Files[0]; 
            file.Stream.Position = 0; 
            var reader = await new StreamReader(file.Stream).ReadToEndAsync(); 
            Console.WriteLine(reader); 
        } 
    } 
} 
 
Regards, 
Sureshkumar P 


Loader.
Up arrow icon