2

I have tried to search for this issue else where in Stack Overflow but couldn't find a proper answer, hence posting my question here. Below is my code, basically i am trying to read content from a file and post it to a web api, and then repeat the same step with another file. The first call passes but the second call fails with the error:

The stream does not support concurrent IO read or write operations at this line requestStream.Write(buffer, 0, bytesRead);.

Could please tell me what am i doing wrong here?

using(FileStream fs = new FileStream(@ "C:\Test1.txt", FileMode.Open, FileAccess.Read)) {

 byte[] buffer = null;
 int bytesRead = 0;
 using(Stream requestStream = request.GetRequestStream()) {
  buffer = new Byte[checked((uint) Math.Min(1024, (int) fs.Length))];
  while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0) {
   requestStream.Write(buffer, 0, bytesRead);
  }
  requestStream.Flush();
 }
}
using(FileStream fs = new FileStream(@ "C:\Test2.txt", FileMode.Open, FileAccess.Read)) {

 byte[] buffer = null;
 int bytesRead = 0;
 using(Stream requestStream = request.GetRequestStream()) {
  buffer = new Byte[checked((uint) Math.Min(1024, (int) fs.Length))];
  while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0) {
   requestStream.Write(buffer, 0, bytesRead);
  }
  requestStream.Flush();
 }
}
Brett Holmes
  • 397
  • 5
  • 20
VIRIYALA NARESH
  • 187
  • 1
  • 4
  • 17
  • 1
    Two identical blocks of code where the only difference is the filename really ought to be in a function. – Matt Burland Apr 02 '18 at 16:33
  • 2
    the problem is within `using (Stream requestStream = request.GetRequestStream())`, do you intend to send both file contents in the same request ? – Volpato Apr 02 '18 at 16:39
  • Sending two text files by writing their bytes to a stream in separate blocks seems overly complicated. You could use `WebClient` or `HttpClient`; their methods are less verbose. And if you're simply merging text content, then you really don't need streams. – Dan Wilson Apr 02 '18 at 16:52
  • Hey Volpato, i guess you are spot on, just realized that. I want to send these files in different requests, based on the response from first request the file in the second request might change. could you please help me how to achieve. I would like to thank others to who provided their valuable suggestions. – VIRIYALA NARESH Apr 02 '18 at 17:26
  • @VIRIYALANARESH See my updated answer – Volpato Apr 02 '18 at 19:32

1 Answers1

2

I believe the problem is happening because you are trying to get a request stream that is no more avaliable:

Try this code:

        List<string> files = new List<String>();
        files.Add(@"C:\Test1.txt");
        files.Add(@"C:\Test2.txt");
        using (Stream requestStream = request.GetRequestStream())
        {
            files.ForEach(fileName =>
            {
                byte[] buffer = null;
                int bytesRead = 0;
                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    buffer = new Byte[checked((uint)Math.Min(1024, (int)fs.Length))];
                    while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                    }
                    requestStream.Flush();
                }
            });
        }

Update: To have control over endpoints and files, try this:

    static void Main(string[] args)
    {
        string result = SendPost(@"C:\Test1.txt", "https://httpbin.org/post");
        if(result.Contains("SUCCESS"))
            SendPost(@"C:\Test2.txt", "https://httpbin.org/anotherpost");

    }

    static string SendPost(string filename, string URL)
    {

        var httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
        httpWebRequest.ContentType = "text/plain";
        httpWebRequest.Method = "POST";

        /*proxy config*/
        WebProxy proxy = new WebProxy();
        Uri newUri = new Uri("http://xxxxxx");
        proxy.Address = newUri;
        httpWebRequest.Proxy = proxy;

        using (var sw = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string[] lines = File.ReadAllLines(filename);
            for(int i=0; i<lines.Length; i++)
                sw.WriteLine(lines[i]);
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }
    }
Volpato
  • 1,543
  • 1
  • 10
  • 10