这类似于接受的答案,但希望更重要。sr.ReadToEnd()
将读取所需的字节:
string myFilePath = @"C:\temp\somefile.txt";
string myEvents = String.Empty;
FileStream fs = new FileStream(myFilePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
myEvents = sr.ReadToEnd();
sr.Close();
fs.Close();
您甚至可以在级联using
语句中执行这些操作。但我想首先描述您写入该文件的方式将如何决定如何从myEvents
字符串中读取内容,并且可能真的是问题所在。我这样写到我的文件中:
using System.Reflection;
using System.IO;
private static void RecordEvents(string someEvent)
{
string folderLoc = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!folderLoc.EndsWith(@"\")) folderLoc += @"\";
folderLoc = folderLoc.Replace(@"\\", @"\"); // replace double-slashes with single slashes
string myFilePath = folderLoc + "myEventFile.txt";
if (!File.Exists(myFilePath))
File.Create(myFilePath).Close(); // must .Close() since will conflict with opening FileStream, below
FileStream fs = new FileStream(myFilePath, FileMode.Append);
StreamWriter sr = new StreamWriter(fs);
sr.Write(someEvent + Environment.NewLine);
sr.Close();
fs.Close();
}
然后我可以使用上面的代码来获取内容的字符串。因为我走得更远并寻找单个字符串,所以我把这段代码放在那个代码之后,在那里:
if (myEvents != String.Empty) // we have something
{
// (char)2660 is ♠ -- I could have chosen any delimiter I did not
// expect to find in my text
myEvents = myEvents.Replace(Environment.NewLine, ((char)2660).ToString());
string[] eventArray = myEvents.Split((char)2660);
foreach (string s in eventArray)
{
if (!String.IsNullOrEmpty(s))
// do whatever with the individual strings from your file
}
}
这很好用。所以我知道myEvents
必须Environment.NewLine
保留字符,因为我能够用该字符替换它(char)2660
并在该字符串上执行一个.Split()
操作,以将其划分为各个段。