开发者

C#: How do i access file in eg. ProjectFolder/file.txt?

开发者 https://www.devze.com 2023-01-12 18:37 出处:网络
i am new to c#. if i have a file in ProjectFolder\\file.txt, how can i access it in code. eg. i want to read a file in code. i remember t开发者_如何学JAVAhe path looks like application://.../file.txt

i am new to c#. if i have a file in ProjectFolder\file.txt, how can i access it in code. eg. i want to read a file in code. i remember t开发者_如何学JAVAhe path looks like application://.../file.txt but i cant remember how exactly


Just set your Copy to Output Directory property of your file to Copy if newer:

C#: How do i access file in eg. ProjectFolder/file.txt?

When you run your program from the output directory, you can simply open the file from the current directory:

string text = File.ReadAllText("file1.txt");


Most people's solutions refer to accessing a file on your file system. However, you mentioned application local URIs, which made me think you are talking about embedded resources. Those resources aren't a separate file on your filesystem. So, the rest of my post is about that.

If you would like to include the file in your assembly, you have to change the properties on the file, changing the BuildAction property to Embedded Resource.

C#: How do i access file in eg. ProjectFolder/file.txt?

From there, you can access it with the resource path, as you described (see Pack URIs: http://msdn.microsoft.com/en-us/library/aa970069.aspx), or you can access it this way:

var stream = System.Reflection.Assembly.GetExecutingAssembly()
    .GetManifestResourceStream("ConsoleApplication1.blah.txt");
var reader = new StreamReader(stream);
Console.WriteLine(reader.ReadToEnd());
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号