C # determine whether a local file or network file exists,
File. Exists method (String)
Determines whether the specified file exists.
Namespace:System. IO
Assembly:Mscorlib (located in mscorlib. dll)
Parameters
-
Path
-
Type: System. String
The file to be checked.
Return Value Type: System. Boolean
If the caller has the required permissions andTrueContains the name of an existing filePathOtherwiseFalse. IfFalseIsPath(An invalid path or zero-length string), this method also returnsNull. If the caller does not have the required permissions to read the specified file, no exception is thrown and the method returnsFalse, Which correspondsPathWhether or not there is anything irrelevant.
1. Determine whether the local file has code:
Static void Main (string [] args ){
String path = "C:/Users/lenovo/Desktop/test.jpg"; if (System. IO. File. Exists (path) {Console. WriteLine ("the local File does exist! ");} Else {Console. WriteLine (" the local file does not exist! ");} Console. ReadKey ();}
It is mainly determined through the Exists method of the System. IO. FIle object.
2. Determine whether the network file has code:
Network Address → request object → determine whether the response status is 200.
Static void Main (string [] args) {string url = @ "https://www.baidu.com/test.png"; // network file address if (JudgeFileExist (url) {Console. writeLine ("the network file does exist! ");} Else {Console. WriteLine (" the network file does not exist! ");} Console. readKey ();} private static bool JudgeFileExist (string url) {try {// create a request object System based on the network address. net. httpWebRequest httpWebRequest = (System. net. httpWebRequest) System. net. webRequest. createDefault (new Uri (url); httpWebRequest. method = "HEAD"; httpWebRequest. timeout = 1000; // return the Boolean value of return (System. net. httpWebResponse) httpWebRequest. getResponse ()). statusCode = System. net. httpStatusCode. OK) ;}catch {return false ;}}