How does default/relative path resolution work in .NET?

后端 未结 4 629
南旧
南旧 2021-02-08 23:31

So... I used to think that when you accessed a file but specified the name without a path (CAISLog.csv in my case) that .NET would expect the file to reside at the same path as

4条回答
  •  既然无缘
    2021-02-09 00:24

    It is based on the current working directory which may or may not be the same as where your application resides, especially if started from a different program or a shortcut with a different working directory.

    Rather than hard code the path, get the path to your program and use it. You can do this with something like this

    Assembly ass = Assembly.GetEntryAssembly();
    string dir = Path.GetDirectoryName(ass.Location);
    string filename = Path.Combine( dir, "CAISLog.csv" );
    

    This assumes that the entry assembly is where your file is. If not, you can change up getting the assembly for something like;

    Assembly ass = Assembly.GetAssembly( typeof( AClassInYourAssembly ) );
    

提交回复
热议问题