Dispose of a RestRequest RestSharp object?

I work with RestSharp and create a RestRequest object to send a FileData to the API. But after receiving the answer, I want to delete the file from my local machine, but when I try to do the same, it will give me the error "The file is being used by another process ." The reason I think is because I cannot dispose of the RestRequest object. Please help me solve the problem. Below is the code. Thanks in Advance .. !!!

   public string PostMultiformDataAPI(Method method, string apiUrl, string data = "", Dictionary<string, string> headers = null)
        {
            string[] files = null;
            try
            {
                RestClient client = new RestClient(apiUrl);
                var request = new RestRequest();
                request.Method = method;

                //Add header values to request
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        request.AddHeader(header.Key, header.Value);
                    }
                }

                string filename = string.Empty;

                if (Directory.Exists(HttpContext.Current.Server.MapPath("/Upload")))
                {
                    files = Directory.GetFiles(HttpContext.Current.Server.MapPath("/Upload"));

                    foreach (string file in files)
                    {
                        request.AddFile(file.Split('/').Last(), file);
                    }
                }

                // execute the request
                IRestResponse response = client.Execute(request);
                var content = response.Content; // raw content as string

                foreach (string file in files)
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    var fileInfo = new FileInfo(file);
                    fileInfo.Refresh();
                    fileInfo.Delete();

                    //File.Delete(file);
                }

                return content;

            }
            finally
            {

            }
        }
+4
source share
1 answer

null , , . . , , .

            // execute the request
            IRestResponse response = client.Execute(request);
            var content = response.Content; // raw content as string

            request = null;
            response = null;

            foreach (string file in files)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                var fileInfo = new FileInfo(file);
                fileInfo.Refresh();
                fileInfo.Delete();
                File.Delete(file);
            }

            return content;
+1

All Articles