Basically I have some code like this that reads the contents of ASCII text file into a List:
List<string> lines = new List<string> ( );
using ( StreamReader sr = File.OpenText ( textfile ) )
{
string s = String.Empty;
while ( ( s = sr.ReadLine ( ) ) != null )
lines.Add ( s );
}
But the thing is when the file is being written by another thread, it throws an exception:
The process cannot access the file 'myfile.txt' because it is being used by another process.
The same thing happens for File.ReadAllLines. Why do these functions lock the file on disk or care that the file is being use by another process?
I just want to read the contents periodically so if it's being used this time, then the next time it will read the updated content. I do this so check if new entries have been added as the user can also add them manually.
What functions I can use to read this file into memory without throwing an exception, or should I use run this code inside try/catch.
This is the latest code:
var fs = new FileStream ( filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite );
using ( StreamReader sr = new StreamReader ( fs ) )
{
string s = String.Empty;
while ( ( s = sr.ReadLine ( ) ) != null )
lines.Add ( s );
}
The code that modifies the file:
public static void RemoveCoinFromBuyOrderLogs ( string symbol )
{
if ( !walletLocked )
{
walletLocked = true;
string [ ] lines = File.ReadAllLines ( walletFilename );
var newlines = lines.Where ( c => !c.StartsWith ( symbol + "USDT" ) && !c.StartsWith ( symbol + "BUSD" ) && !c.StartsWith ( symbol + "USDC" ) && !c.StartsWith ( symbol + "TUSD" ) ).Select ( c => c ).ToList ( );
File.WriteAllLines ( walletFilename, newlines );
using ( FileStream fs = File.Open ( walletFilename, FileMode.OpenOrCreate ) )
{
StreamWriter sw = new StreamWriter ( fs );
sw.AutoFlush = true;
newlines.ForEach ( r => sw.WriteLine ( r ) );
}
walletLocked = false;
}
}
public static void AddCoinToOrderLogs ( string newOrder, long orderId )
{
if ( !walletLocked )
{
var lines = Utility.ReadAllLines ( walletFilename );
lines = lines.Select ( line => line.Replace ( "\r", "" ) ).ToList ( );
lines = lines.Where ( line => line != "" ).Select ( line => line ).ToList ( );
var fields = lines.Select ( line => line.Split ( '\t' ) ).ToList ( );
bool duplicate = false;
foreach ( var field in fields )
{
if ( field.Length >= 5 )
{
long id = Convert.ToInt64 ( field [ 4 ] );
if ( id == orderId )
duplicate = true;
}
}
if ( !duplicate )
{
lines.Add ( newOrder );
lines.Sort ( );
walletLocked = true;
File.WriteAllLines ( walletFilename, lines );
walletLocked = false;
}
}
}