我想从一个正常工作的url中获取文件名,但我不知道所有可能的情况。我有下面的方法,但它并不适用于所有情况。如果以前有人这样做过,请帮助
public static string getFileName(HttpWebResponse response, string requestUrl)
{
var cd = response.Headers["Content-Disposition"];
var loc = response.Headers["Location"];
if (!string.IsNullOrEmpty(cd))
{
var disp = new ContentDisposition(cd);
return Encoding.UTF8.GetString(Encoding.GetEncoding(1254).GetBytes(disp.FileName));
}
else if (!string.IsNullOrEmpty(loc))
return Path.GetFileName(loc);
else
return Path.GetFileName(response.ResponseUri.OriginalString);
}
UPDATE:添加的示例案例
案例示例1:
http://www.example.com/some/path/to/a/file.xml?foo=bar#test
filename = file.xml
案例2:
http://www.example.com/some/path/to/a/watch?filename=file.xml&foo=bar
filename = file.xml
我自己写了一个解决方案,它似乎适用于所有情况(至少适用于我认为的情况(。
public static class FileNameHelper
{
public static string GetFileName(HttpWebResponse resp)
{
var cdHeader = resp.Headers["Content-Disposition"];
var location = resp.Headers["Location"];
if (!string.IsNullOrEmpty(cdHeader))
{
var pattern = string.Format("filename[^;=n]*=((['"]).*?{0}|[^;n]*)", Regex.Escape("2"));
var omitPattern = "filename[^;n=]*=(([^'"])*'')?";
var properFormat = Encoding.UTF8.GetString(Encoding.GetEncoding("ISO-8859-1").GetBytes(cdHeader));
properFormat = HttpUtility.UrlDecode(properFormat);
properFormat = properFormat.Replace(""", "");
var matches = Regex.Matches(properFormat, pattern);
if (matches.Count > 0)
{
var filename = matches.Cast<Match>().Last().Value;
filename = Regex.Replace(filename, omitPattern, "");
var temp = HttpUtility.UrlDecode(filename);
return temp.ReplaceInvalidChars();
}
}
if (!string.IsNullOrEmpty(location))
{
var locUri = new Uri(location);
var first = Path.GetFileName(locUri.LocalPath);
if (first.IsCorrectFilename())
{
return HttpUtility.UrlDecode(first);
}
else
{
first = Path.GetFileName(locUri.AbsolutePath);
return HttpUtility.UrlDecode(first.ReplaceInvalidChars());
}
}
else
{
var first = Path.GetFileName(resp.ResponseUri.LocalPath);
if (first.IsCorrectFilename())
{
return HttpUtility.UrlDecode(first);
}
else
{
first = Path.GetFileName(resp.ResponseUri.AbsolutePath);
return HttpUtility.UrlDecode(first.ReplaceInvalidChars());
}
}
}
public static bool HasExtension(this string filename)
{
return !string.IsNullOrEmpty(Path.GetExtension(filename));
}
public static bool HasInvalidChar(this string filename)
{
return Path.GetInvalidFileNameChars().Any(x => filename.Contains(x));
}
public static string ReplaceInvalidChars(this string filename)
{
foreach (var c in Path.GetInvalidFileNameChars())
{
filename = filename.Replace(c.ToString(), "");
}
return filename;
}
public static bool IsCorrectFilename(this string filename)
{
return filename.HasExtension() && !filename.HasInvalidChar();
}
}
如果您没有文件夹/文件的权限,您将得到一个异常,并且不会返回任何内容。在发生异常后,您必须使用如下代码才能继续
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace SAveDirectoriesXml
{
class Program
{
const string FILENAME = @"c:temptest.xml";
const string FOLDER = @"c:temp";
static XmlWriter writer = null;
static void Main(string[] args)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
writer = XmlWriter.Create(FILENAME, settings);
writer.WriteStartDocument(true);
DirectoryInfo info = new DirectoryInfo(FOLDER);
WriteTree(info);
writer.WriteEndDocument();
writer.Flush();
writer.Close();
Console.WriteLine("Enter Return");
Console.ReadLine();
}
static long WriteTree(DirectoryInfo info)
{
long size = 0;
writer.WriteStartElement("Folder");
try
{
writer.WriteAttributeString("name", info.Name);
writer.WriteAttributeString("numberSubFolders", info.GetDirectories().Count().ToString());
writer.WriteAttributeString("numberFiles", info.GetFiles().Count().ToString());
writer.WriteAttributeString("date", info.LastWriteTime.ToString());
foreach (DirectoryInfo childInfo in info.GetDirectories())
{
size += WriteTree(childInfo);
}
}
catch (Exception ex)
{
string errorMsg = string.Format("Exception Folder : {0}, Error : {1}", info.FullName, ex.Message);
Console.WriteLine(errorMsg);
writer.WriteElementString("Error", errorMsg);
}
FileInfo[] fileInfo = null;
try
{
fileInfo = info.GetFiles();
}
catch (Exception ex)
{
string errorMsg = string.Format("Exception FileInfo : {0}, Error : {1}", info.FullName, ex.Message);
Console.WriteLine(errorMsg);
writer.WriteElementString("Error",errorMsg);
}
if (fileInfo != null)
{
foreach (FileInfo finfo in fileInfo)
{
try
{
writer.WriteStartElement("File");
writer.WriteAttributeString("name", finfo.Name);
writer.WriteAttributeString("size", finfo.Length.ToString());
writer.WriteAttributeString("date", info.LastWriteTime.ToString());
writer.WriteEndElement();
size += finfo.Length;
}
catch (Exception ex)
{
string errorMsg = string.Format("Exception File : {0}, Error : {1}", finfo.FullName, ex.Message);
Console.WriteLine(errorMsg);
writer.WriteElementString("Error", errorMsg);
}
}
}
writer.WriteElementString("size", size.ToString());
writer.WriteEndElement();
return size;
}
}
}