I have files that I want to delete. Connection can be from file sharing, http, and ftp.
Example of files to delete:
//mytest//delete//filename.bin
ftp://mytest/delete/filename.bin
http://mytest/delete/filename.bin
Here's what I did:
Uri target = new Uri(#"ftp://mytest/delete/filename.bin");
FileInfo fi = new FileInfo(target.AbsoluteUri);
fi.Delete();
The error I get is:
The given paths format is not supported
Is there a single code that can delete in all these file types?
I have created a simple code for this task(based on thread response).
This is the input:
Uri target = new Uri(#"ftp://tabletijam/FileServer/upload.bin");
Uri target = new Uri(#"http://tabletijam/FileServer/upload.bin");
Uri target = new Uri(#"\\tabletijam\FileServer\upload.bin");
This is the code:
bool DeleteFileOnServer(Uri serverUri)
{
if (serverUri.Scheme == Uri.UriSchemeFtp)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
lblStatus.Content = response.StatusDescription;
response.Close();
return true;
}
else if (serverUri.Scheme == Uri.UriSchemeFile)
{
System.IO.File.Delete(serverUri.LocalPath);
return true;
}
else if (serverUri.Scheme == Uri.UriSchemeHttp || serverUri.Scheme == Uri.UriSchemeHttps)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Http.DeleteFile;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
lblStatus.Content = response.StatusDescription;
response.Close();
return true;
}
else
{
lblStatus.Content = "Unknown uri scheme.";
return false;
}
}
Ftp and File deleted successfully. WebRequestMethods.Http does not contain DeleteFile.
So my question is, how do I delete file from this URI?
http://tabletijam/FileServer/upload.bin
Because FileInfo only works with local files. For each connection you will need a special implementation.
For FTP: (example from MSDN)
public static bool DeleteFileOnServer(Uri serverUri)
{
// The serverUri parameter should use the ftp:// scheme.
// It contains the name of the server file that is to be deleted.
// Example: ftp://contoso.com/someFile.txt.
//
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse) request.GetResponse();
Console.WriteLine("Delete status: {0}",response.StatusDescription);
response.Close();
return true;
}
Using the \\server... notation, you can delete file (that you have access) to on remote servers.
Using FTP, you should the FtpWebRequest.
For HTTP, you could issue a DELETE request, using HttpWebRequest.
For both FTP and HTTP, you might need to supply a username and password. Also normally HTTP servers are not configured to delete files when receiving a DELETE request by default.
For a whole lot of reasons, no, there is not a single unified way you can delete files via each of these protocols.
You could abstract this away into some implementation of your own, however, using an implementation specific to each of the protocols you want to support...
how do i delete file from this uri?
request.Method = "DELETE";
Also, there's a different header supported by WebDAV for controlling the delete...
No, this is not possible. FTP and HTTP are protocols that you are required to stick to. Even though you may be able to delete files when viewing FTP folders in the Explorer doesn't mean it works from C#, too, because the Explorer uses an integrated FTP client. Deleting files via HTTP like that isn't possible at all.
Related
I've written a site in ASP.NET which uses FTPWebRequest to download a text file from an FTP server every 15 seconds. When I run it on my computer, it works just fine. When I upload it to our server, the FTP download fails. No exception, it just returns 0 values.
I thought there might be an issue with the firewall, so I disabled the Windows firewall, and disabled outgoing firewall, same problem. Tried both active and passive FTP. Is it possible I need to change some settings in IIS Manager?
Running IIS 10 on Server 2012 R2, on the same VM with Exchange 2016.
Part of the code:
public static string[] GetTXT()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("FTP address");
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.UsePassive = false; //tried it with true as well
request.Credentials = new NetworkCredential("user", "pass");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string result = (reader.ReadToEnd());
}
Eventually discovered I was publishing the site in a subfolder.
The root folder probably contained an older version.
Anyway, thanks for the help!
If just a download from the server FTP, I recommend this class WebClient implemented by Microsoft for your method.
It maybe resolves your problem.
public static string[] GetTXT()
{
using (WebClient client = new WebClient())
{
var path = #"C:\local\path\file.txt";
client.Credentials = new NetworkCredential("log", "pass");
client.DownloadFile("ftp://ftp.example.com/remote/path/file.txt", path);
}
if (File.Exists(path))
{
return File.ReadAllLines(path);
}
//return something
}
I have a function that is coded to get the Content-Type of a web file.
Here is the function:
public string GetContentTypeOfUri(string uri)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "HEAD";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
var contentType = response.Headers["Content-Type"];
return (contentType);
}
}
catch (Exception ex)
{
return "error";
}
}
Rather than writing a whole different function to detect if a web file exists, how can I calculate if a file exists from the same code as used to get the Content-Type?
If I use a uri of a file that does not exist, an exception occurs. The ex.HResult equals -2146233079 when this exception occurs, with a message = "The remote name could not be resolved: '[address name]'".
Is it safe to say that when an exception occurs, and the ex.HResult equals -2146233079, the file does not exist?
Is there an easier/better way to work this out?
Thanks in advance
EDIT
Here is the HttpClient code that I have:
public async Task<string> GetContentTypeAsync(string uri)
{
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Method = new HttpMethod("HEAD");
var response = await httpClient.SendAsync(request);
string contentType = response.Content.Headers.ContentType.ToString();
return contentType;
}
}
Your example web address does inform me that the address does not exist, however, if I have a web address that does not exist such as http://www.usa.canon.com/app/html/HDV/HG10/images/hg10_sample_image_03.jpg5, I am getting a StatusCode of OK, as a Text content type is returned as a custom error page.
There are two possible "not exists" scenarios. It sounds like you've identified one of them - when the server name in the URL is incorrect and so the request cannot even be sent.
But you're not accounting for the other error - that you can reach a remote server but it denies all knowledge of a specific file. For that scenario, you ought to be checking for status 404 on the response.
For cleaner handling of your current scenario (server doesn't exist) you could use the Uri class to extract the Host name from the uri string and perform a manual DNS lookup - which would allow you to code for this likely scenario without having to catch exceptions - which is generally frowned upon when its an expected scenario.
I'm having trouble getting Proxy Automatic Configuration (PAC) in IE options to work as expected using .Net WebRequest.
According to this article:
Proxy Detection
Take the Burden Off Users with Automatic Configuration in .NET
The system proxy should be set by default with to each WebRequest.
That's how the proxy.js pac file looks like:
function FindProxyForURL(url, host)
{
return "PROXY ProxyServerName:3118; DIRECT;";
}
I also took a look at this post: How should I set the default proxy to use default credentials?
Which suggests to add this in the app.config:
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
Adding this did not help.
I created a small console application just to test this out.. here it is:
static void Main(string[] args)
{
HttpWebRequest request = null;
try
{
String resolvedAddress = WebRequest.DefaultWebProxy.GetProxy(new Uri("http://www.google.com")).ToString();
Console.WriteLine("Proxy for address is: " + resolvedAddress);
Uri m_URLToTest = new Uri("http://www.google.com");
request = WebRequest.Create(m_URLToTest) as HttpWebRequest;
request.Method = "GET";
request.KeepAlive = false;
request.Timeout = 5000;
request.Proxy = WebRequest.DefaultWebProxy;
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string message = reader.ReadToEnd();
}
catch (Exception ex)
{
Console.Write("Exception");
}
}
The output:
Proxy for address is http://www.google.com
instead of Proxy for address is ProxyServerName:3118
It happens only when using auto configuration script...
Did I miss anything? Please help!
Found the solution!
It is really important that the mime type of the PAC file would be: [Content-type: application/x-ns-proxy-autoconfig]
Other mime types might not work.
Make sure using fiddler2 (with cache disabled) that the mime type is appropriate.
Some configurations might show Content-Type: text/plain which is bad.
Make sure you have checked Internet (Client & Server) and Private Networks (Client & Server) capabilities in Package.appxmanifest.
[Source]
I am developing a tool for validation of links in url entered. suppose i have entered a url
(e.g http://www-review-k6.thinkcentral.com/content/hsp/science/hspscience/na/gr3/se_9780153722271_/content/nlsg3_006.html
) in textbox1 and i want to check whether the contents of all the links exists on remote server or not. finally i want a log file for the broken links.
You can use HttpWebRequest.
Note four things
1) The webRequest will throw exception if the link doesn't exist
2) You may like to disable auto redirect
3) You may also like to check if it's a valid url. If not, it will throw UriFormatException.
UPDATED
4) Per Paige suggested , Use "Head" in request.Method so that it won't download the whole remote file
static bool UrlExists(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "HEAD";
request.AllowAutoRedirect = false;
request.GetResponse();
}
catch (UriFormatException)
{
// Invalid Url
return false;
}
catch (WebException ex)
{
// Valid Url but not exists
HttpWebResponse webResponse = (HttpWebResponse)ex.Response;
if (webResponse.StatusCode == HttpStatusCode.NotFound)
{
return false;
}
}
return true;
}
Use the HttpWebResponse class:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://www.gooogle.com/");
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
if (response.StatusCode == HttpStatusCode.NotFound)
{
// do something
}
bool LinkExist(string link)
{
HttpWebRequest webRequest = (HttpWebRequest) webRequest.Create(link);
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
return !(webResponse.StatusCode != HttpStatusCode.NotFound);
}
Use an HTTP HEAD request as explained in this article: http://www.eggheadcafe.com/tutorials/aspnet/2c13cafc-be1c-4dd8-9129-f82f59991517/the-lowly-http-head-reque.aspx
Make a HTTP request to the URL and see if you get a 404 response. If so then it does not exist.
Do you need a code example?
If your goal is robust validation of page source, consider usign a tool that is already written, like the W3C Link Checker. It can be run as a command-line program that handles finding links, pictures, css, etc and checking them for validity. It can also recursively check an entire web-site.
This is my current function below. Its used to create a folder in a document library in SharePoint but using web dav functionality, which is easier than MOSS stuff.
I need to find a way to determine reliably if the folder already exists... Notice now I am relying on that try catch, but this means that ANY protocol exception will not throw an error, so its not a reliable function. How can I check using web dav if a folder exists?
private void createFolderUsingWebDav(string siteAddress, string listAddress, string folderName)
{
//Check Databox Folder Exists
string folderAddress = siteAddress + #"/" + listAddress + #"/" + folderName;
HttpWebResponse response;
try
{
HttpWebRequest request = (System.Net.HttpWebRequest)HttpWebRequest.Create(folderAddress);
request.Credentials = wsLists.Credentials; // CredentialCache.DefaultCredentials;
request.Method = "MKCOL";
response = (System.Net.HttpWebResponse)request.GetResponse();
response.Close();
}
catch (WebException ex)
{
if (ex.Status != WebExceptionStatus.ProtocolError)
{
throw ex;
}
}
}
Essentially I want the unwrapped version of what this product achieves here:
http://www.independentsoft.de/webdav/tutorial/exists.html
If you do a PROPFIND on the url, you will get a 404 back if the folder does not exist.
Make the PROPFIND look something like this (only showing the relevant headers)
PROPFIND /yourfolder HTTP/1.1
Content-Type: application/xml
<?xml version="1.0"?>
<propfind xmlns="DAV:">
<prop>
<resourcetype />
</prop>
</propfind>
404 means the resource doesn't exist, 207 means it does.
PROPFIND is your friend: the DAV:resourcetype property (http://greenbytes.de/tech/webdav/rfc4918.html#rfc.section.15.9) has a DAV:collection child element for collections. Just retrieve it using PROPFIND with DAV:allprop or DAV:prop (both described in http://greenbytes.de/tech/webdav/rfc4918.html#rfc.section.9).