StreamReader在读取文本文件时会锁定它.
我可以强制StreamReader以"只读"或"非锁定"模式工作吗?
我的解决方法是将文件复制到临时位置并从那里读取,但我更愿意直接使用StreamReader.任何替代建议?
背景:
我写了一个小应用程序来从日志文件中获取一些统计信息.该文件不断被外部程序更新(每秒几次),可以调用AAXXYY.
查看输出表明我的应用程序可能正在锁定文件并阻止AAXXYY写入.
这就是我正在做的事情
private void btnGetStats_Click(object sender, EventArgs e)
{
int countStarts = 0;
int countEnds = 0;
IList<string> sessions = new List<string>();
using(StreamReader stRead = new StreamReader(openFileDialog1.FileName,Encoding.Unicode))
{
while(!stRead.EndOfStream)
{
string line = stRead.ReadLine();
if(line.Contains("Session start"))
{
countStarts++;
sessions.Add(line.Substring(line.IndexOf("["), line.LastIndexOf("]") - line.IndexOf("[")));
}
if (line.Contains("Session end"))
{
countEnds++;
sessions.Remove(line.Substring(line.IndexOf("["), line.LastIndexOf("]") - line.IndexOf("[")));
}
}
}
txtStarts.Text = countStarts.ToString();
txtEnds.Text = countEnds.ToString();
txtDifference.Text = (countStarts - countEnds).ToString();
listBox1.DataSource = sessions;
}
Run Code Online (Sandbox Code Playgroud) 大家好我需要做的是跟踪我从流阅读器中读取的行的位置当我说reader.ReadLine()
我需要知道文件中该行的位置时我还希望能够从中读取文件我之前跟踪的位置.
这可能吗?如果是这样请协助.
非常感谢帮助
提前致谢.
一个例子(可能不是现实生活,但要说明我的观点):
public void StreamInfo(StreamReader p)
{
string info = string.Format(
"The supplied streamreaer read : {0}\n at line {1}",
p.ReadLine(),
p.GetLinePosition()-1);
}
Run Code Online (Sandbox Code Playgroud)
GetLinePosition
这是streamreader的虚构扩展方法.这可能吗?
当然,我可以自己计算,但这不是问题.
我不熟悉加密,正在使用以下方法加密文件:
private static void encryptFile(string filePath, byte[] password, byte[] salt)
{
Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(password, salt, 1000);
AesManaged algorithm = new AesManaged();
byte[] rgbKey = rdb.GetBytes(algorithm.KeySize / 8);
byte[] rgbIV = rdb.GetBytes(algorithm.BlockSize / 8);
GCHandle keyHandle = GCHandle.Alloc(rgbKey, GCHandleType.Pinned);
GCHandle IVHandle = GCHandle.Alloc(rgbIV, GCHandleType.Pinned);
ICryptoTransform cryptoAlgorithm = algorithm.CreateEncryptor(rgbKey, rgbIV);
using (FileStream readStream = File.Open(filePath, FileMode.Open))
{
using (FileStream writeStream = new FileStream(filePath + ".enc", FileMode.Create, FileAccess.Write))
{
using (CryptoStream cryptoStream = new CryptoStream(writeStream, cryptoAlgorithm, CryptoStreamMode.Write))
{
while (readStream.Position < …
Run Code Online (Sandbox Code Playgroud)