问题
I am working with RestSharp and create object of RestRequest for sending FileData to API. But after getting response I want to delete the file from my local machine but when I try to do the same it gives me the error "File is being used by other process". The reason I think is that I am unable to dispose the object of RestRequest. Please help me to solve it. 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
{
}
}
回答1:
You just need to assign null to request object instance to remove the reference it has to file. Worked for me. Please let me know if it works for you.
// 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;
来源:https://stackoverflow.com/questions/26907879/dispose-object-of-restrequest-restsharp