I want to check if a file exists in the same URL but not on the server. What I meant was, say if I have a domain https://example.com/ and a folder in the domain https://example.com**/s3files/** automatically points or redirect to S3 so that https://example.com/**s3files/test.png**, downloads a file from s3 directly.
How can I test in my controller that said file exists?
I'm trying to do something like this
fileName = $"/s3files/{fileName}";
if (!File.Exists(path))
return "/assets/images/no-image.png";
return fileName;
But I'm not sure if It's correct since File.Exist
checks the local directory of the server if the file exists in the '/s3files' subdirectory.
Since my controller doesn't know about the routing part and its current domain URL, how can I check if the file exists?
CodePudding user response:
Maybe this will help...
public static bool checkIfFileExists(string url)
{
bool found = false;
var request = WebRequest.Create(url);
request.Method = "HEAD";
request.Timeout = 30;
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
found = true;
}
catch (WebException webException)
{
}
finally
{
if (response != null)
{
response.Close();
}
}
return found;
}
CodePudding user response:
you can send a HEAD request, it will check the metadata of the file without actually downloading it.
Here is the code for you.
using (var client = new HttpClient())
{
var fileUrl = $"https://example.com/s3files/{fileName}";
var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, fileUrl));
if (response.StatusCode == HttpStatusCode.OK)
{
// File exists
return fileUrl;
}
else
{
// File doesn't exist
return "/assets/images/no-image.png";
}
}
It will return the status code 200 if the file is present else it will return 404.