PDA

View Full Version : Hỏi về cách đọc nội dung một file mà mình đã đính kèm vào project c# winform



rungxanh252000
30-03-2009, 19:08
thông thường để đọc một file thì :

StreamReader rd = new StreamReader(@"c:\Controller.txt");
string content = rd.ReadToEnd();
MessageBox.Show(content);

nhưng bây giơ file Controller.txt mình đã add vào trong project .
vậy khi đọc nó thế nào vậy: nhờ các bạn giúp mình với nhé thanks
đây là hình ảnh mình đã add file controller vào prjoect của mình
http://img26.imageshack.us/img26/6703/fileyek.jpg
mình đã đọc thế này nhưng nó khônng được:
StreamReader rd = new StreamReader(@"template\Controllers\Controller.txt");
string content = rd.ReadToEnd();

MessageBox.Show(content);

Squall_Lionhart
30-03-2009, 20:10
bạn làm như sau:
1. Trong cửa sổ properties của file Controller.txt, đổi thuộc tính "Build Action" thành "Embedded Resource"
2. Code


System.IO.Stream stream = System.Reflection.Assembly.GetEntryAssembly().GetM anifestResourceStream(@"GeneratorMVC.template.Controllers.Controller.txt");
System.IO.StreamReader rd = new System.IO.StreamReader(stream);
string content = rd.ReadToEnd();

rungxanh252000
30-03-2009, 20:21
mình bắt đầu làm theo cách bạn làm đây , ko biết được hay không nhưng cảm ơn bạn rất nhiều, mình làm một phần mềm nhỏ có thê general cho asp.net MVC, chỉ còn mắc vấn đề này nữa thôi, nếu được thành công thì cảm ơn bạn nhiều nhé.
Best regards.

vutranhung
31-03-2009, 10:13
StreamReader rd = new StreamReader(@"template\Controllers\Controller.txt ");
thì thực chất đường dẫn thực của bạn khi chạy chương trình sẽ là
tenchuongtrinh\Bin\Realese(Debug)\template\Control lers\Controller.txt nên sẽ ko tìm thấy do vậy không đọc được.
Thông thường các người ta sẽ để file này trong thư mục Bin\Realse(Debug) nhưng nếu cậu để nó trong thư mục như hình của cậu thì cậu phải thiết lập thuộc tính cho file Controller.txt để khi built nó sẽ copy file của cậu vào đúng theo đường dẫn tenchuongtrinh\Bin\Realese(Debug)\template\Control lers\Controller.txt thì khi đó mới đọc được. Để làm điều này thì trong cửa sổ properties của file Controller.txt bạn chọn thuộc tính Copy to Output Directory là Copy always. Chúc bạn thành công

doanhathanh
01-04-2009, 21:02
global::GeneratorMVC.template.Controllers.Controll er.txt

đơn giản vậy thôi.
Với các file bạn lưu trong Resources cũng tưong tự như vậy:

global::[Tên project].Properties.Resources.[tên file cần truy cập]