C#: How do i access file in eg. ProjectFolder/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:
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.
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());
精彩评论