Home > Net >  overwrite first line of textfile (c#)
overwrite first line of textfile (c#)

Time:10-19

I have a textfile (obj-file) which is auto generated.

It looks like this:

# File generated by IfcOpenShell v0.7.0-e508fb44
g 2O2Fr$t4X7Zf8NOew3FNtn
s 1
v 0 -0.417 0
v 0 -5.55111512312578e-17 0
v 2.63496916504281 -5.55111512312578e-17 0
v 2.63496916504281 -0.417 0
v 2.63496916504281 -0.417 0
v 2.63496916504281 -5.55111512312578e-17 0
v 2.63496916504281 -5.55111512312578e-17 2.42
v 2.63496916504281 -0.417 2.42
...

I need to insert the string mtllib ./model_0.mtl at the beginning of the file. Since the first line is always a comment i thought i could overwrite it like this.

# File generated by IfcOpenShell v0.7.0-e508fb44

mtllib ./model_0.mtl

The problem is I don't know how to achive this, how do I open the file in special way? I want to avoid reading the whole file in changing a few characters and writing the whole file out..

this is similar, but does not seem to help too much (I'm using c#) Textfiles C Editing the very first line

CodePudding user response:

You can try using Linq; if file is not that large

using System.IO;
using System.Linq;

...

string fileName = @"c:\myFile.txt";

var newLines = new string[] {"mtllib ./model_0.mtl"} // first line
  .Concat(File
    .ReadLines(fileName) // all file
    .Skip(1))            // except the very first line
    .ToList();

File.WriteAllLines(fileName, newLines);

If file is large and so .ToList() - materialization - is not a good option we can save the file and then rename it:

using System.IO;
using System.Linq;

...

string fileName = @"c:\myFile.txt";

var newLines = new string[] {"mtllib ./model_0.mtl"} // first line
  .Concat(File
    .ReadLines(fileName) // all file
    .Skip(1));           // except the very first line
    
// Save under different name
File.WriteAllLines(fileName   "~", newLines);

File.Move(fileName   "~", fileName, true);

CodePudding user response:

If the file is not too large simply use

string[] lines = File.ReadAllLines(path); 
lines[0] = "mtllib ./model_0.mtl"; // you might want to check if lines.Length > 0 
File.WriteAllLines(path, lines);

CodePudding user response:

String newLine="mtllib ./model_0.mtl" ;

string content = File.ReadAllText(Path);
content = newLine   "\n"   content;      
File.WriteAllText(Path, content);
  • Related