处理RestRequest RestSharp的对象?

时间:2014-11-13 11:28:42

标签: c# file file-upload webrequest restsharp

我正在使用RestSharp并创建RestRequest对象以将FileData发送到API。但是在得到回复之后我想从我的本地机器上删除该文件但是当我尝试做同样的事情时它会给我错误“文件被其他进程使用”。我认为的原因是我无法处理RestRequest的对象。请帮我解决一下。下面是代码。在此先感谢.. !!!

   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
            {

            }
        }

1 个答案:

答案 0 :(得分:1)

您只需要为请求对象实例分配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;