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;
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);
}
}
IRestResponse response = client.Execute(request);
var content = response.Content;
foreach (string file in files)
{
GC.Collect();
GC.WaitForPendingFinalizers();
var fileInfo = new FileInfo(file);
fileInfo.Refresh();
fileInfo.Delete();
}
return content;
}
finally
{
}
}
source
share