title: 500 internal server error when writing file to the server
body: <p>I'm developing an android app with Xamarin that uploads file to the server. My server is asp.net based and is hosted by azure. Xamarin throws this error when the code tries to write the file to the server directory. The code I'm using to post the file to the server is as follows:</p>
  
  <pre><code>        public async Task&lt;HttpResponseMessage&gt; UploadFile(byte[] file)
      {
          videoThumbName = Guid.NewGuid().ToString();
          var progress = new System.Net.Http.Handlers.ProgressMessageHandler();
  
          progress.HttpSendProgress += progress_HttpSendProgress;
  
          using (var client = HttpClientFactory.Create(progress))
          {
              client.BaseAddress = new Uri(GlobalVariables.host);
  
              // Set the Accept header for BSON.
              client.DefaultRequestHeaders.Accept.Clear();
              client.DefaultRequestHeaders.Accept.Add(
                      new MediaTypeWithQualityHeaderValue("application/bson"));
  
              var request = new uploadFileModel { data = file, dateCreated = DateTime.Now, fileName = fileName, username = loggedUser, VideoThumbName = videoThumbName};
  
              // POST using the BSON formatter.
              MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
              var m = client.MaxResponseContentBufferSize;
              var result = await client.PostAsync("api/media/upload", request, bsonFormatter);
  
              return result.EnsureSuccessStatusCode();
          }
      }
  </code></pre>
  
  <p>I've tried using a try catch block and the weird thing is that the exception is caught even after the file has been written to the path and I get the 500 internal server error. So far every file I tried to upload was save to the path but I can't figure out why is error occurring. </p>
  
  <p>My server side code looks like the following:</p>
  
  <pre><code>       [HttpPost]
      [Route("upload")]
      public async Task&lt;HttpResponseMessage&gt; Upload(uploadFileModel model)
      {
  
  
          var result = new HttpResponseMessage(HttpStatusCode.OK);
  
          if (ModelState.IsValid)
          {
              string thumbname = "";
              string resizedthumbname = Guid.NewGuid() + "_yt.jpg";
  
              string FfmpegPath = Encoding_Settings.FFMPEGPATH;
  
              string tempFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/tempuploads"), model.fileName);
              string pathToFiles = HttpContext.Current.Server.MapPath("~/tempuploads");
              string pathToThumbs = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/thumbs");
              string finalPath = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/flv");
              string resizedthumb = Path.Combine(pathToThumbs, resizedthumbname);
  
  
              var outputPathVid = new MediaFile { Filename = Path.Combine(finalPath, model.fileName) };
              var inputPathVid = new MediaFile { Filename = Path.Combine(pathToFiles, model.fileName) };
              int maxWidth = 380;
              int maxHeight = 360;
  
              var namewithoutext = Path.GetFileNameWithoutExtension(Path.Combine(pathToFiles, model.fileName));
              thumbname = model.VideoThumbName;
              string oldthumbpath = Path.Combine(pathToThumbs, thumbname);
  
  
              var fileName = model.fileName;
              try
              {
                  File.WriteAllBytes(tempFilePath, model.data);
              }
              catch (Exception e)
              {
                  Console.WriteLine(e.Message);
              }
  
  
  
              if (model.fileName.Contains("audio"))
              {
                  File.WriteAllBytes(Path.Combine(finalPath, model.fileName), model.data);
  
                  string audio_thumb = "mic_thumb.jpg";
                  string destination = Path.Combine(pathToThumbs, audio_thumb);
                  string source = Path.Combine(pathToFiles, audio_thumb);
                  if (!System.IO.File.Exists(destination))
                  {
                      System.IO.File.Copy(source, destination, true);
                  }
  
  
                  Video_Struct vd = new Video_Struct();
                  vd.CategoryID = 0; // store categoryname or term instead of category id
                  vd.Categories = "";
                  vd.UserName = model.username;
                  vd.Title = "";
                  vd.Description = "";
                  vd.Tags = "";
                  vd.OriginalVideoFileName = model.fileName;
                  vd.VideoFileName = model.fileName;
                  vd.ThumbFileName = "mic_thumb.jpg";
                  vd.isPrivate = 0;
                  vd.AuthKey = "";
                  vd.isEnabled = 1;
                  vd.Response_VideoID = 0; // video responses
                  vd.isResponse = 0;
                  vd.isPublished = 1;
                  vd.isReviewed = 1;
                  vd.Thumb_Url = "none";
                  //vd.FLV_Url = flv_url;
                  vd.Embed_Script = "";
                  vd.isExternal = 0; // website own video, 1: embed video
                  vd.Type = 0;
                  vd.YoutubeID = "";
                  vd.isTagsreViewed = 1;
                  vd.Mode = 0; // filter videos based on website sections
                  long videoid = VideoBLL.Process_Info(vd, false);
              }
  </code></pre>
  
  <p>The exception doesn't reveal much for me to understand the issue. Strangely I don't get any errors when I'm sending request to the local server. Any idea what might be wrong here?</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>The exception no longer occurring when I get the internal server error at this line of my code <code>using (var engine = new Engine())</code> This is a library I'm trying to use to encode a media file. If everything works on the local server then why doesn't it on the live server :/</p>
  
  <pre><code>using (var engine = new Engine())
                  {
                      engine.GetMetadata(inputPathVid);
  
                      // Saves the frame located on the 15th second of the video.
                      var outputPathThumb = new MediaFile { Filename = Path.Combine(pathToThumbs, thumbname+".jpg") };
                      var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(0), CustomHeight = 360, CustomWidth = 380 };
                      engine.GetThumbnail(inputPathVid, outputPathThumb, options);
  
                  }
  
                  Image image = Image.FromFile(Path.Combine(pathToThumbs, thumbname+".jpg"));
  
                  //var ratioX = (double)maxWidth / image.Width;
                  //var ratioY = (double)maxHeight / image.Height;
                  //var ratio = Math.Min(ratioX, ratioY);
  
                  var newWidth = (int)(maxWidth);
                  var newHeight = (int)(maxHeight);
  
                  var newImage = new Bitmap(newWidth, newHeight);
                  Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
                  Bitmap bmp = new Bitmap(newImage);
                  bmp.Save(Path.Combine(pathToThumbs, thumbname+"_resized.jpg"));
  
                  //File.Delete(Path.Combine(pathToThumbs, thumbname));
  
                  using (var engine = new Engine())
                  {
  
                      var conversionOptions = new ConversionOptions
                      {
                          VideoSize = VideoSize.Hd720,
                          AudioSampleRate = AudioSampleRate.Hz44100,
                          VideoAspectRatio = VideoAspectRatio.Default
                      };
  
                      engine.GetMetadata(inputPathVid);
                      engine.Convert(inputPathVid, outputPathVid, conversionOptions);
  
                  }
  
                  File.Delete(tempFilePath);
  
                  Video_Struct vd = new Video_Struct();
                  vd.CategoryID = 0; // store categoryname or term instead of category id
                  vd.Categories = "";
                  vd.UserName = model.username;
                  vd.Title = "";
                  vd.Description = "";
                  vd.Tags = "";
                  vd.Duration = inputPathVid.Metadata.Duration.ToString();
                  vd.Duration_Sec = Convert.ToInt32(inputPathVid.Metadata.Duration.Seconds.ToString());
                  vd.OriginalVideoFileName = model.fileName;
                  vd.VideoFileName = model.fileName;
                  vd.ThumbFileName = thumbname+"_resized.jpg";
                  vd.isPrivate = 0;
                  vd.AuthKey = "";
                  vd.isEnabled = 1;
                  vd.Response_VideoID = 0; // video responses
                  vd.isResponse = 0;
                  vd.isPublished = 1;
                  vd.isReviewed = 1;
                  vd.Thumb_Url = "none";
                  //vd.FLV_Url = flv_url;
                  vd.Embed_Script = "";
                  vd.isExternal = 0; // website own video, 1: embed video
                  vd.Type = 0;
                  vd.YoutubeID = "";
                  vd.isTagsreViewed = 1;
                  vd.Mode = 0; // filter videos based on website sections
                  //vd.ContentLength = f_contentlength;
                  vd.GalleryID = 0;
                  long videoid = VideoBLL.Process_Info(vd, false);
  
              }`enter code here`
  </code></pre>