替换文件路径中的分隔符字符

sal*_*ere 4 c# replace delimiter visual-studio-2008

我正在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);
Run Code Online (Sandbox Code Playgroud)

LeB*_*leu 6

你确定问题是反斜杠吗?反斜杠是字符串中的转义字符,因此如果您将其添加到字符串中,则必须将其键入为"\\"而不是"\".(如果你不使用@)请注意,调试器经常以你将它放在代码中的方式显示字符串,使用转义字符,而不是直接字符.

根据文档,Page.Request.PhysicalPath返回您所在的特定文件的路径,而不是目录.Directory.Exists仅在您为其提供目录而不是文件时才为真.File.Exists()是否返回true?


Igb*_*man 5

首先,呼叫fullpath.Replace()无效fullpath; 它返回一个新字符串.此外,当您的字符串文字中包含\(反斜杠)时,您需要告诉编译器您没有尝试使用转义序列:

fullpath = fullpath.Replace(@"\\", @"\"); 
Run Code Online (Sandbox Code Playgroud)

@意思是"请从字面上(逐字)把这个字符串".换句话说,"当我说反斜杠时,我的意思是反斜杠!"

请参阅http://msdn.microsoft.com/en-us/library/362314fe.aspx.

编辑:

正如LeBleu所提到的,您在完整的文件路径上调用Directory.Exists().这不起作用; 您需要从路径中提取目录部分.试试这个:

if (!Directory.Exists(Path.GetDirectoryName(fullpath)))
{
     ...
}
Run Code Online (Sandbox Code Playgroud)