我正在 VS 2008 中开发一个 C# Web 应用程序。我让用户选择一个输入文件,然后将文件路径存储在一个字符串变量中。但是,它将这条路径存储为"C:\\folder\\..."
。所以我的问题是如何将此文件路径转换为单个“\”?
谢谢大家的帮助!请原谅我,因为我是 ASP.NET 开发的新手。这是我在上下文中的更多代码。首先我想看看该目录是否存在。我想如果我检查文件是否存在,我就不必检查这个。但这应该仍然有效,对吗?目前我的“路径”字符串变量没有按我需要的方式显示。我不知道如何表述这个声明。最终我想执行 ReadAllText 语句(参见最后一行)。
protected void btnAppend_Click(object sender, EventArgs e)
{
string fullpath = Page.Request.PhysicalPath;
string fullPath2 = fullpath.Replace(@"\\", @"\");
if (!Directory.Exists(fullpath2))
{
string msg = "<h1>The upload path doesn't exist: {0}</h1>";
Response.Write(String.Format(msg, fullpath2));
Response.End();
}
string path = "@" + fullpath2 + uploadFile.PostedFile.FileName;
if (File.Exists(path))
{
// Create a file to write to.
try
{
StreamReader sr = new StreamReader(path);
string s = "";
while(sr.Peek() > 0)
s = sr.ReadLine();
sr.Close();
}
catch (IOException exc)
{
Console.WriteLine(exc.Message + "Cannot open file.");
return;
}
}
if (uploadFile.PostedFile.ContentLength > 0)
{
inputfile = System.IO.File.ReadAllText(path);
您确定问题是反斜杠吗?反斜杠是字符串中的转义字符,因此如果将其添加到字符串中,则必须将其键入为“\\”而不是“\”。 (如果不使用@)请注意,调试器经常按照您在代码中放置的方式显示字符串,并使用转义字符,而不是直接显示。
根据文档 http://msdn.microsoft.com/en-us/library/system.web.httprequest.physicalpath.aspx、Page.Request.PhysicalPath 返回您所在的特定文件的路径,而不是目录。仅当您给它一个目录而不是一个文件时,Directory.Exists 才是 true。 File.Exists() 返回 true 吗?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)