Home > front end >  Can't get absolute path to file C#
Can't get absolute path to file C#

Time:03-12

enter image description here

I have very simple program. Here I set the absolute path,but C# thinks that it's a relative path and try to load the file from project directory: C:\Users\Gleb Kozyukevich\source\repos\ChangeDir\ChageDir\bin\Debug\netcoreapp3.1\C:\test\test.txt

The path really exists.

What did I miss? I can't get understand

CodePudding user response:

There are multiple ways you try.

  1. Give file path like
string sourceFilePath  = @"C:\test\test.txt";
  1. Use System.IO.Path.Combine
string sourceFilePath = System.IO.Path.Combine(new []{"C:","test","test.txt"});

CodePudding user response:

That is very strange. I've reproduced the code the way I think you wrote it and the result is just fine.

Here the code I wrote:

using System;
using System.IO;

namespace ReadAllLines
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var lines = File.ReadAllLines(@"c:\temp\test.txt");
            
            Console.ReadKey();
        }
    }
}

Here's the result: enter image description here

  • Related