I want to add some text at a specific position in a specific line. This is what I got so far:
public void AddSomeTextToFile(string FilePath, int LineNumber, int IndexInLine, string TextToAdd)
{
string[] WholeFile = File.ReadAllLines(FilePath);
WholeFile[LineNumber - 1] = WholeFile[LineNumber - 1].Insert(IndexInLine, TextToAdd);
File.WriteAllLines(FilePath, WholeFile);
}
This, code, however, has some issues with encoding.
For example, text that was becomes
. I've tried using
Encoding.UTF8
and Encoding.Unicode
, both with no success.
Is there any way to insert some text into a file and preserve and special characters?
Solution
Based on floele's code, this is the code that solved my problems:
public void AddSomeTextToFile(string FilePath, int LineNumber, int IndexInLine, string TextToAdd)
{
byte[] bytes = File.ReadAllBytes(FilePath);
List<List<byte>> lines = bytes.SplitOn((byte)'\n').ToList();
byte[] bytesToInsert = Encoding.Default.GetBytes(TextToAdd);
lines[LineNumber - 1].InsertRange(IndexInLine, bytesToInsert);
File.WriteAllBytes(FilePath, lines.SelectMany(x => x).ToArray());
}
static class EnumerableExtensions
{
public static IEnumerable<List<T>> SplitOn<T>(
this IEnumerable<T> source,
T delimiter)
{
var list = new List<T>();
foreach (var item in source)
{
if (delimiter.Equals(item))
{
list.Add(item);
yield return list;
list = new List<T>();
}
else
{
list.Add(item);
}
}
yield return list;
}
}