Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing delimiter characters in file path

I'm developing a C# web application in VS 2008. I let the user select an input file and then I store the file path in a string variable. However, it stores this path as "C:\\folder\\...". So my question is how do I convert this file path into single "\"?

Thank you guys for all your helps! Please forgive me as I am a newbie to ASP.NET development. This is more of my code in context. First I want to see if the directory exists. I guess I don't have to check this if I check if the file exists. But this should still work right? And currently my "path" string variable is not showing up the way I need it to. I'm not sure how to formulate this statement. Eventually I want to execute the ReadAllText statement (see the last line).

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);
like image 819
salvationishere Avatar asked Dec 22 '22 03:12

salvationishere


1 Answers

Are you sure the problem is the backslashes? Backslash is an escape character in strings, such that if you were adding it in a string you have to type it as "\\" rather than "\". (if you don't use @) Note that the debugger frequently displays the string the way you would put it in code, with the escape characters, rather than direct.

According to the documentation, Page.Request.PhysicalPath returns the path to the specific file you are in, not the directory. Directory.Exists is only true if you give it a directory, not a file. Does File.Exists() return true?

like image 74
LeBleu Avatar answered Jan 02 '23 00:01

LeBleu