Graph: downloading a text file throws exception

Giorgio Sfiligoi 371 Reputation points
2025-04-05T12:23:42.1533333+00:00

I am trying to download a simple text file from OneDrive:

// get the DriveItem for 'test.txt' (Id = T_ID)
var file = await graphClient.Drives["me"].Items[T_ID].GetAsync();                                 
Debug.Assert(file != null && file.File != null);
sb.Append(file.Name?.ToString());
sb.AppendLine("  Last modified: " + file.LastModifiedDateTime.ToString());
// download and display content
sb.AppendLine("File content:\n");
var stream = await graphClient.Drives["me"].Items[T_ID]
                              .Content
                              .GetAsync();
if (stream == null) sb.AppendLine("Stream is null");
else 
{
    try
    {
        using var reader = new StreamReader(stream);
        sb.AppendLine($"{reader.ReadToEnd()}");
    }
    catch (Exception ex)
    {
        sb.AppendLine($"{ex.Message}");
    }
} 

'test.txt' simply contains the string "This is a test document", T_ID is its Id in the Drive.

I get:

Exception of type 'Android.OS.NetworkOnMainThread Exception' was thrown

I tried to modify the Android manifest including android:usesCleartextTraffic="true" - same result.

Notes:

  1. In Windows machine it works without any problem
  2. Uploading the same file does not throw any exception.
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
13,510 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

  2. Giorgio Sfiligoi 371 Reputation points
    2025-04-08T14:19:17.08+00:00

    The stream returned by Graph must be copied to a local stream:

                                        var memstrem = new MemoryStream();
                                        stream.CopyTo(memstrem);
                                        memstrem.Position = 0;
                                        using var reader = new StreamReader(memstrem);
                                        sb.AppendLine(reader.ReadToEnd());
    
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.