Streamreader/Streamwriter

G

Guest

Using vb.net, I am using Streamreader to read a text file and searching for a
line to delete, the I close the file and open it as a streamwriter so I can
put the new file back to disk without the line that I deleted. Can someone
tell me how I can do this without having to close the file first before
switching to streamwriter, because closing the file allows someone else to
grab the file before I put the new information back. Thanks if any one can
help me!

Joe
 
S

Stelrad Doulton

Try using a temp file, something like this: (sorry no VB)
string path = @"c:\somefile.txt";
string tempPath = path + ".tmp";
string line = null;
StreamReader reader = null;
StreamWriter writer = null;


try
{
reader = new StreamReader(path);
writer = new StreamWriter(tempPath);

while((line = reader.ReadLine()) != null)
{
if(line != "useless information")
{
writer.WriteLine(line);
}
}
}
catch
{
return;
}
finally
{
if(reader != null)
reader.Close();

if(writer != null)
writer.Close();
}

File.Copy(tempPath, path, true);
File.Delete(tempPath);
 
R

rossum

Using vb.net, I am using Streamreader to read a text file and searching for a
line to delete, the I close the file and open it as a streamwriter so I can
put the new file back to disk without the line that I deleted. Can someone
tell me how I can do this without having to close the file first before
switching to streamwriter, because closing the file allows someone else to
grab the file before I put the new information back. Thanks if any one can
help me!

Joe

I have done something similar in C#. Basically I start by renaming
the original copy to a backup version, then I open both the backup
version and a new file with the original name, reading from the backup
and writing to the new file simultaneously. That way the old version
is renamed and the new version is not available for anyone else until
you have finished writing to it.

Below is a simplified version:
(Warning, this has been edited and not compiled so there may be
typos.)

// Backup copy of original.
string fileName = "my_original_file.txt";
string backupName = fileName + ".bak";
if (File.Exists(backupName)) { File.Delete(backupName); }
File.Move(fileName, backupName); // Move(,) renames the file.

// Copy required lines from the backup to the new file
FileInfo originalFile = new FileInfo(backupName);
StreamReader inStream = originalFile.OpenText();
StreamWriter outStream = new StreamWriter(fileName);
string thisLine = inStream.ReadLine();
while (thisLine != null) {
if (toBeCopied(thisLine)) { outStream.WriteLine(thisLine); }
thisLine = inStream.ReadLine();
}
inStream.Close();
outStream.Close();

HTH

rossum


The ultimate truth is that there is no ultimate truth
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top