Hi,
Is it possible to update a record of a txt file in C#? In VB, we can do:
Open inFile For Random As #1 Len = 1156
Put #1 , recNum, outLine
Close #1
Here recNum is the specific record number which we want to update, outLine is the new record.
My question is that in C# do we have any way to do it or not? Or C# have any other way to update a record just like update in DB file.
So far, I can figure out a way is to write all the records from beginning to recNum -1, then write record recNum and then write the balance. finianlly delete the old file and rename the new file. This is very dummy way. I hope somebody can give me a better ideal.
Thanks you very much.
Loading
will hePosted Oct 5, 2006, 11:57 AM
I found the answer by myself. Below is the code:
///
///here, the data structure is fixlength and end by Crlf char("\r\n").
///
public void updatedIt(string inFile, int recLen, int recNum)
{
// int byteLen, byteStartNum;
FileStream fileInput = new FileStream(inFile, FileMode.Open, FileAccess.ReadWrite);
BinaryWriter wr = new BinaryWriter(fileInput);
try
{
fileInput.Seek((recNum-1)*(recLen), SeekOrigin.Begin);
byte[] b = new byte[recLen-2];
ASCIIEncoding temp = new ASCIIEncoding();
b = temp.GetBytes(recStr);
fileInput.Write(b, 0, recLen-2);
}
catch(IOException)
{
//close stream if no records in file
MessageBox.Show("records number out of range","",MessageBoxButtons.OK,
MessageBoxIcon.Information);
fileInput.Close();
}
fileInput.Close();
}
Any questions, email to me: [email protected]