Code similar to the following:
Copy codeThe Code is as follows:
Uri uri = new Uri (targetUrl); // the absolute path of the file corresponding to targetUrl
System. Net. HttpWebRequest request = (HttpWebRequest) WebRequest. Create (uri );
Request. Method = "PUT ";
Request. Credentials = System. Net. CredentialCache. DefaultCredentials;
Request. ContentLength = stream. Length;
File Name: fr#322.16.xls (excel attachment)
After being uploaded to the server, it turns into fr.xls, and the file name is incorrect, causing download failure.
The reason is that some Uris include segment identifiers or queries. The segment identifier is any text in the URI following the digit sign (#) and is stored in the Fragment attribute.
The query information is followed by the question mark (?) in the URI (?) Any text after the Query is stored in the Query attribute. That is to say, the Uri class splits and stores the content after the file path.
In addition, the relevant attribute in the Uri is read-only, so it can only be modified through other paths.
Solution:
UriBuilder class, which provides a custom constructor for the Uniform Resource Identifier (URI) and modifies the Uri Of The URI class. It has the same functions as Uri, but its related attributes can be set.
The modified code is as follows:
Copy codeThe Code is as follows:
Uri uri = WebHelper. ProcessSpecialCharacters (targetUrl); // the absolute path of the file corresponding to targetUrl
System. Net. HttpWebRequest request = (HttpWebRequest) WebRequest. Create (uri );
Request. Method = "PUT ";
Request. Credentials = System. Net. CredentialCache. DefaultCredentials;
Request. ContentLength = stream. Length;
/// <Summary>
/// When the uploaded or downloaded file name contains a special character "#", You need to execute the following functions for processing.
/// </Summary>
/// <Param name = "Url"> </param>
/// <Returns> </returns>
Private static Uri ProcessSpecialCharacters (string Url)
{
Uri uriTarget = new Uri (Url );
If (! Url. Contains ("#"))
{
Return uriTarget;
}
UriBuilder msPage = new UriBuilder ();
MsPage. Host = uriTarget. Host;
MsPage. Scheme = uriTarget. Scheme;
MsPage. Port = uriTarget. Port;
MsPage. Path = uriTarget. LocalPath + uriTarget. Fragment;
MsPage. Fragment = uriTarget. Fragment;
Uri uri = msPage. Uri;
Return uri;
}
Uri uri = new Uri (targetUrl); // the absolute path of the file corresponding to targetUrl