ما هي أفضل طريقة لقراءة محتويات ملف نصي إلى سلسلة في .الشبكة ؟
-
09-06-2019 - |
سؤال
يبدو أنه ينبغي أن يكون هناك ما هو أقل من هذا:
private string LoadFromFile(string path)
{
try
{
string fileContents;
using(StreamReader rdr = File.OpenText(path))
{
fileContents = rdr.ReadToEnd();
}
return fileContents;
}
catch
{
throw;
}
}
المحلول
أولا: العنوان يسأل عن "كيفية كتابة محتويات strnig إلى ملف نصي" ولكن التعليمات البرمجية المثال هو "كيفية قراءة محتويات ملف نصي إلى سلسلة.
الجواب على السؤالين:
using System.IO;
...
string filename = "C:/example.txt";
string content = File.ReadAllText(filename);
File.WriteAllText(filename, content);
انظر أيضا ReadAllLines/WriteAllLines و ReadAllBytes/WriteAllBytes إذا بدلا من سلسلة تريد صفيف سلسلة أو صفيف بايت.
نصائح أخرى
string text = File.ReadAllText("c:\file1.txt");
File.WriteAllText("c:\file2.txt", text);
أيضا تحقق من ReadAllLines/WriteAllLines و ReadAllBytes/WriteAllBytes
ليس هناك نقطة في هذا الاستثناء معالج.فإنه لا يفعل شيئا.هذا هو مجرد shorterned نسخة من التعليمات البرمجية الخاصة بك, لا بأس:
private string LoadFromFile(string path)
{
using(StreamReader rdr = File.OpenText(path))
return rdr.ReadToEnd();
}
الملف.ReadAllText() ربما ؟
ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/fxref_mscorlib/html/4803f846-3d8a-de8a-18eb-32cfcd038f76.htm إذا كان لديك VS2008 مساعدة المثبتة.
لا تنتمي إلى StackOverflow