?
Solved

Editing a txt file

Posted on 2005-04-28
11
Medium Priority
?
258 Views
Last Modified: 2010-04-16
Hello guys & gals,

I have an ini file which I need to modify.

One of the way I know is to read the file using StreamReader, then modify the string you read it in, and then write it back using StreamWriter.

I only need to find two words on two lines in the text, which will be on the different lines but might not be separated with spaces or anything, like dirbase=blah-blah-blah. If I find this stuff in my file, I just need to comment this two lines out using # character, like

// if it was
dirbase = c:\blah-blah-blah
// it will be
#dirbase = c:\blah-blah-blah

Do I really need to read aaaaall file and do it all in the string? Is there any way to do someting like:

Read line by line,
If line is found, modify the line - e.g. Write back the line

regards
0
Comment
Question by:Yurich
  • 5
  • 3
  • 2
  • +1
11 Comments
 
LVL 22

Expert Comment

by:Mohammed Nasman
ID: 13890572
StreamReader class has a method called ReadLine, you could use it to read line by line
0
 
LVL 21

Author Comment

by:Yurich
ID: 13890615
it's not the point...
of course i can read it line by line the whole file, my question was - do I have to read the whole file in order to edit two line of the file.
0
 
LVL 22

Expert Comment

by:Mohammed Nasman
ID: 13890839
I don't think there's a way to load a specific line of text file without loading it

but you could loop through the file using ReadLine, till you find the line you want to modify, then stop reading the file, it' lucky you will not load the whole file, but in the worse case, you will load it
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 21

Author Comment

by:Yurich
ID: 13890887
again...
the whole point of reading is writing back - if i read 10 lines out of 20, then modify whatever I want to modify, I'll have to write it back, using StreamWriter( result ) and here my question comes again!

Can I write only editted lines into the file?

If I can - that's the answer and that's what I'm after.

If I can't - there is no point of reading a part of the file if I'll have to load the whole thing again after modifying...

regards
0
 
LVL 1

Expert Comment

by:pbowens
ID: 13891534
Hi there,

.NET DOES support random access in files, but not in the way you are using them in your examples. You can set up record structures and write record-at-a-time, and also perform seeks and writeback single records.

Generally though, .NET has tried to replace this kind of file access with the new XML file classes. If you are still trying to read and write to a traditional ini file, you can either read the whole thing into memory, manipulate it and write it back out, or use an API call to the "GetPrivateProfileString" and "SetPrivateProfileString", but from what I have seen, this can be a nightmare to implement.

As I said, I'm not sure what you are trying to accomplish with this ini file - and moving to XML may not be an option for you, but it is worth checking out due to the rich functionailty that .NET offers in this area. If it's not an option, stick with the whole file read and write. It will be the easiest and quickest way to accomplish what you are after.
0
 
LVL 10

Expert Comment

by:heintalus
ID: 13891582
Hi Yurick

Just thinking out loud
Could you use the FileStream class, use indexof on it's ToString method to find the position of the value your after within the stream, then use the FileStreams Seek method to set the current position of this stream to the given value & then insert your # at that position ?

I haven't tried this out but thought it might give you some ideas and an avenue to try.

HTH
Andy
0
 
LVL 21

Author Comment

by:Yurich
ID: 13892009
2hintalus,
sounds intriguing but I'm afraid I didn't get it straight...

I do use FileStream class:

FileStream file = new FileStream( filePath );

then, if I use file.ToString() it will return me "System.IO.FileStream" :(( ...

Didi you mean something else??

If I use read, it'll read the whole thing again but this time just as a byte[]...

regards
0
 
LVL 10

Accepted Solution

by:
heintalus earned 1000 total points
ID: 13892499
Hi Yurich

I was thinking of something along these lines but having tried it, it replaces the value a the specified position in the file rather than inserting the character, maybe you can play with it & get it to work.

FileStream fs = new FileStream("C:\\test\\test.ini",FileMode.OpenOrCreate);
StreamReader sr = new StreamReader(fs);
                  
int i = sr.ReadToEnd().ToString().IndexOf("dirbase");

fs.Seek(Convert.ToInt32(i)-1,SeekOrigin.Begin);
try
{
      fs.WriteByte(Convert.ToByte('#'));
}
catch (Exception exc)
{
      MessageBox.Show(exc.ToString());
}
            
fs.Close();

HTH
Andy
0
 
LVL 21

Author Comment

by:Yurich
ID: 13906146
Hello Andy,
it almost works.

The problem is it overrides the character we're writing it into (i - 1), which is carriage return in my case but it doesn't matter what character since we don't want to override any existent data but just insert a new char...

any ideas?

regards
0
 
LVL 10

Expert Comment

by:heintalus
ID: 13907204
Hi Yurich

I couldn't find a way of inserting the character, as you say it only overwrites the character at the present position which is a pain, it would be great if they had an AppendByte method 8).

The only way I could think of which is a bit messy is to create a StringBuilder append the # to it & then a substring from the StreamReader from the position of the i to the end of the stream & then use the FileStreams.WriteByte method to write the StringBuilders.ToString output back into the Filestream at the position of i.

As I said rather messy but it should work.  I'm not on my development machine at the moment so can't look for any other possibilities.

regards
Andy
0
 
LVL 21

Author Comment

by:Yurich
ID: 13907772
thanks guys,
let's say we found a way of overriding bytes in the file without reading it all ;)
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Screencast - Getting to Know the Pipeline
Suggested Courses

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question