Read file in C# sent with Requests Python

637 Views Asked by At

I'm trying to read a file test.txt using C# that I send using Requests in Python :

test.txt

Hello

Client.py

import requests

if __name__ == '__main__':
    url = 'http://localhost:1234/'
    headers = {'auth':'myAuth'}
    r = requests.post(url, headers=headers,files={'test.txt':open('./test.txt','rb')})
    print r.text

Then I try to retrieve the data on the server side in C# :

Server.cs

[...]
public void ProcessRequest(HttpListenerContext context)
{
    Stream mStream = myHttpRequest.InputStream;
    int content_size = int.Parse(myHttpRequest.Headers["content-length"]);
    byte[] data = new BinaryReader(mStream).ReadBytes(content_size);
    string str = System.Text.Encoding.Default.GetString(data);
    Console.WriteLine(str);
}

What I get from the Console.WriteLine(str) is : enter image description here

But I don't manage to get only the Hello part. How can I do that ?

1

There are 1 best solutions below

0
On

I manage to get the code from here working by modifying the following lines :

// Skip four lines (Boundary, Content-Disposition, Content-Type, and a blank)
for (Int32 i = 0; i < 4; i++)

to

// Skip 3 lines (Boundary, Content-Disposition and a blank)
for (Int32 i = 0; i < 3; i++)