Modify FileStream - c#

I'm working now on a class that will allow editing very big text files (4Gb+). Well it may sound a little stupid but I do not understand how I can modify text in a stream.
Here is my code:
public long Replace(String text1, String text2)
{
long replaceCount = 0;
currentFileStream = File.Open(CurrentFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
using (BufferedStream bs = new BufferedStream(currentFileStream))
using (StreamReader sr = new StreamReader(bs))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains(text1))
{
line.Replace(text1, text2);
// Here I should save changed line
replaceCount++;
}
}
}
return replaceCount;
}

You are not replacing it anywhere in your code. You should save all the text and then write it again to the file. Like,
public long Replace(String text1, String text2)
{
long replaceCount = 0;
currentFileStream = File.Open(CurrentFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
StringBuilder sb = new StringBuilder();
using (BufferedStream bs = new BufferedStream(currentFileStream))
using (StreamReader sr = new StreamReader(bs))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string textToAdd = line;
if (line.Contains(text1))
{
textToAdd = line.Replace(text1, text2);
// Here I should save changed line
replaceCount++;
}
sb.Append(textToAdd);
}
}
using (FileStream fileStream = new FileStream(filename , fileMode, fileAccess))
{
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.Write(sb.ToString());
streamWriter.Close();
fileStream.Close();
}
return replaceCount;
}

Related

Read and overwrite at the same FileStream

I'm using a FileStream to lock the File to be not writeable for other processes and also read and write to it, I'm using following method for it:
public static void ChangeOrAddLine(string newLine, string oldLine = "")
{
string filePath = "C:\\test.txt";
FileMode fm = FileMode.Create;
//FileMode fm = FileMode.OpenOrCreate;
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
using (StreamReader sr = new StreamReader(fs))
using (StreamWriter sw = new StreamWriter(fs))
{
List<string> lines = sr.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.None).ToList();
bool lineFound = false;
if (oldLine != "")
for (int i = 0; i < lines.Count; i++)
if (lines[i] == oldLine)
{
lines[i] = newLine;
lineFound = true;
break;
}
if (!lineFound)
lines.Add(newLine);
sw.Write(string.Join("\r\n", lines));
}
}
I want to overwrite it with the new content but i don't find the right FileMode, using FileMode.OpenOrCreate just appends the new content to the old and FileMode.Create deletes the file-content at the time, the FileStream fm has been initialized, so the file is empty.
I need to just clear the old content at the moment, when i write the new content to it without losing the write-lock on it during the method is running.
OpenOrCreate just appends ...
Because you don't reposition after the reading.
That also shows the main problem with your approach: The FileStream only has one Position, and the Reader and the Writer heavily use caching.
However, as long as you want to replace everything and really need that locking scheme:
using (FileStream fs = new FileStream(filePath,
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
{
using (StreamReader sr = new StreamReader(fs))
{
... // all the reading
}
fs.Position = 0;
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(string.Join("\r\n", lines));
}
fs.SetLength(fs.Position); // untested, something along this line
}
and maybe you have to convince the sw and sr to leave their stream open.
But I have to note that the FileShare.Read flag doesn't make too much sense in this scenario. A reader could see al sorts of inconsistent data, including torn lines and broken UTF8 characters.

BinaryFile Read to byte[]

I have binary file
BinaryWriter binwriter = new BinaryWriter(File.Open("C:\\temp\\Users.bin", FileMode.Create));
binwriter.Write(buff);
binwriter.Close();
It works, but how can I read data from this file?
I need to read new line each time, while it is not end of file.
BinaryReader binreader = new BinaryReader(File.Open("C:\\temp\\Users.bin", FileMode.Open));
byte[] m = binreader.ReadBytes(??????); //I to read only 1 line to m, and then I need to read again new line to m.
Binary file doesn't have the concept of a "line", however you can try to read it like a text file by doing this way :
using (var streamReader = new StreamReader(filePath))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.WriteLine(sr.ReadLine());
}
}
you can of course adapt it to your needs instead of printing it on the Console.

How to write into an existing textfile in windows phone?

If this is the code in opening a textfile "word.txt" in my solution explorer.
Stream txtStream = Application.GetResourceStream(new Uri("/sample;component/word.txt", UriKind.Relative)).Stream;
using (StreamReader sr = new StreamReader(txtStream))
{
string jon;
while (!sr.EndOfStream)
{
jon = sr.ReadLine();
mylistbox.ItemSource = jon;
}
}
How do i write and append in the existing textfile?
Here is an example
public static void WriteBackgroundSetting(string currentBackground)
{
const string fileName = "RecipeHub.txt";
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if(myIsolatedStorage.FileExists(fileName))
myIsolatedStorage.DeleteFile(fileName);
var stream = myIsolatedStorage.CreateFile(fileName);
using (StreamWriter isoStream = new StreamWriter(stream))
{
isoStream.WriteLine(currentBackground);
}
}
}

IsolatedStorage ArgumentNullException

I don't see what's the matter here:
Constructor:
IsolatedStorageFile isf;
public FileManagement()
{
isf = IsolatedStorageFile.GetUserStoreForApplication();
}
when I save files:
public bool saveCredentials(String username, String userpass)
{
bool res = false;
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("usercred.custom",
FileMode.Create, FileAccess.Write, isf));
writeFile.WriteLine(username);
writeFile.WriteLine(userpass);
res = true;
return res;
}
and when I try to read them:
public String readUsername()
{
String username = "";
IsolatedStorageFileStream fileStream = isf.OpenFile("usercred.custom", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fileStream);
username = reader.ReadLine();
return username;
}
Reading returns null.
I try to save a file and write something into it, but it somehow doesn't work.
You have to close your streams. Please add reader.Close(), writefile.Close() and fileStream.Close() before return and try again.

How can I read a text file without locking it?

I have a windows service writes its log in a text file in a simple format.
Now, I'm going to create a small application to read the service's log and shows both the existing log and the added one as live view.
The problem is that the service locks the text file for adding the new lines and at the same time the viewer application locks the file for reading.
The Service Code:
void WriteInLog(string logFilePath, data)
{
File.AppendAllText(logFilePath,
string.Format("{0} : {1}\r\n", DateTime.Now, data));
}
The viewer Code:
int index = 0;
private void Form1_Load(object sender, EventArgs e)
{
try
{
using (StreamReader sr = new StreamReader(logFilePath))
{
while (sr.Peek() >= 0) // reading the old data
{
AddLineToGrid(sr.ReadLine());
index++;
}
sr.Close();
}
timer1.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
using (StreamReader sr = new StreamReader(logFilePath))
{
// skipping the old data, it has read in the Form1_Load event handler
for (int i = 0; i < index ; i++)
sr.ReadLine();
while (sr.Peek() >= 0) // reading the live data if exists
{
string str = sr.ReadLine();
if (str != null)
{
AddLineToGrid(str);
index++;
}
}
sr.Close();
}
}
Is there any problem in my code in reading and writing way?
How to solve the problem?
You need to make sure that both the service and the reader open the log file non-exclusively. Try this:
For the service - the writer in your example - use a FileStream instance created as follows:
var outStream = new FileStream(logfileName, FileMode.Open,
FileAccess.Write, FileShare.ReadWrite);
For the reader use the same but change the file access:
var inStream = new FileStream(logfileName, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite);
Also, since FileStream implements IDisposable make sure that in both cases you consider using a using statement, for example for the writer:
using(var outStream = ...)
{
// using outStream here
...
}
Good luck!
Explicit set up the sharing mode while reading the text file.
using (FileStream fs = new FileStream(logFilePath,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs))
{
while (sr.Peek() >= 0) // reading the old data
{
AddLineToGrid(sr.ReadLine());
index++;
}
}
}
new StreamReader(File.Open(logFilePath,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
-> this doesn't lock the file.
The problem is when you are writing to the log you are exclusively locking the file down so your StreamReader won't be allowed to open it at all.
You need to try open the file in readonly mode.
using (FileStream fs = new FileStream("myLogFile.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs))
{
while (!fs.EndOfStream)
{
string line = fs.ReadLine();
// Your code here
}
}
}
I remember doing the same thing a couple of years ago. After some google queries i found this:
FileStream fs = new FileStream(#”c:\test.txt”,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite);
i.e. use the FileShare.ReadWrite attribute on FileStream().
(found on Balaji Ramesh's blog)
Have you tried copying the file, then reading it?
Just update the copy whenever big changes are made.
This method will help you to fastest read a text file and without locking it.
private string ReadFileAndFetchStringInSingleLine(string file)
{
StringBuilder sb;
try
{
sb = new StringBuilder();
using (FileStream fs = File.Open(file, FileMode.Open))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (StreamReader sr = new StreamReader(bs))
{
string str;
while ((str = sr.ReadLine()) != null)
{
sb.Append(str);
}
}
}
}
return sb.ToString();
}
catch (Exception ex)
{
return "";
}
}
Hope this method will help you.

Categories