C# - How to Copy a Single Excel Worksheet from One Workbook to Another

How to insert characters to a file using C#

Filesystems do not support "inserting" data in the middle of a file. If you really have a need for a file that can be written to in a sorted kind of way, I suggest you look into using an embedded database.

You might want to take a look at SQLite or BerkeleyDB.

Then again, you might be working with a text file or a legacy binary file. In that case your only option is to rewrite the file, at least from the insertion point up to the end.

I would look at the FileStream class to do random I/O in C#.

How to insert characters at particular locations in text file

import io

# watch the `r` in header, footer & adding to raw_data lines, `r` is raw, it's meant to take strings as is
header= r'''\begin{longtable}{|c | c |}
\hline
$V_{out}$(in V) & $I_{out}$(in mA) \\ \hline'''

footer = r'''\caption{\\Output Characteristics for low input}
\label{tab:output@low}
\end{longtable}'''

with open('raw_data.txt', encoding='utf8') as raw_data, open('result.txt', 'w', encoding='utf8') as result:
result.write(header)

for line in raw_data.readlines():
datapoint1, datapoint2 = line.split()
result.write(datapoint1 + '& ' + datapoint2 + r'\\ \hline' + '\n')

result.write(footer)

Insert character at nth position for each line in a text file

You don't need to use Regular Expressions here. One simple way is to use File.ReadAllLines to read all lines and simply add your char at desired position as in following code:

var sb = new StringBuilder();
string path = @"E:\test\test.txt"; //input file
string path2 = @"E:\test\test2.txt"; //the output file, could be same as input path to overwrite
string charToInsert = " ";
string[] lines = File.ReadAllLines(path);
foreach (string line in lines)
{
sb.AppendLine(line.Length > 8 ? line.Substring(0, 8) + charToInsert + line.Substring(9) : line);
}
File.WriteAllText(path2, sb.ToString());

Here I use a different path for output for test purposes (don't overwrite the input)

EDIT:

The modified code to loop through all .txt files in a folder:

string path = @"C:\TestFolder";
string charToInsert = " ";
string[] allFiles = Directory.GetFiles(path, "*.txt", SearchOption.TopDirectoryOnly); //Directory.EnumerateFiles
foreach (string file in allFiles)
{
var sb = new StringBuilder();
string[] lines = File.ReadAllLines(file); //input file
foreach (string line in lines)
{
sb.AppendLine(line.Length > 8 ? line.Substring(0, 8) + charToInsert + line.Substring(9) : line);
}
File.WriteAllText(file, sb.ToString()); //overwrite modified content
}

How to insert a character after every n characters in a huge text file using C#?

void InsertACharacterNoStringAfterEveryNCharactersInAHugeTextFileUsingCSharp(
string inputPath, string outputPath, int blockSize, string separator)
{
using (var input = File.OpenText(inputPath))
using (var output = File.CreateText(outputPath))
{
var buffer = new char[blockSize];
int readCount;
while ((readCount = input.ReadBlock(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, readCount);
if (readCount == buffer.Length)
output.Write(separator);
}
}
}

// usage:
InsertACharacterNoStringAfterEveryNCharactersInAHugeTextFileUsingCSharp(
inputPath, outputPath, 3, Environment.NewLine);

Inserting a tab character into text using C#

Try using the \t character in your strings

C#: Inserting Variable into Text File

I ran your code sample on my machine and it works how you expect. I recommend you look at the content of you str1.txt file and confirm the path resolves properly. If none of that works, look at the encoding of the file.

Also watch out for stray { or } characters in your file. Escape them by doubling them up or replace your code with

string str1 = "hello {0}";
string str2 = "world";
string final = str1.replace("{0}", str2); //Output should be "hello world"

Insert string into a filepath string before the file extension C#

Use the static methods in the System.IO.Path class to split the filename and add a suffix before the extension.

string AddSuffix(string filename, string suffix)
{
string fDir = Path.GetDirectoryName(filename);
string fName = Path.GetFileNameWithoutExtension(filename);
string fExt = Path.GetExtension(filename);
return Path.Combine(fDir, String.Concat(fName, suffix, fExt));
}

string newFilename = AddSuffix(filename, String.Format("({0})", crcValue));

How to insert special character like 'ü ','ä ' in database using c#

I was passing only stream object. Needed to pass the encoding parameter to StreamReader.

using (var streamReader = new StreamReader(jsonStream, Encoding.GetEncoding("iso-8859-1")))

Inserting text at index in an file; problems with encoding

Encoding.UTF8 is actually the default encoding used by WriteAllLines and ReadAllLines. So if reading and writing using this encoding "corrupts" your data, you need to use a different one.

You need to determine what the original encoding of the file located at FilePath is and then specify it like this

File.ReadAllLines(FilePath, *encoding*);  
File.WriteAllLines(FilePath, WholeFile, *encoding*);

A likely encoding would be Encoding.Default (windows-1252), try it out. If that doesn't work, you have to check how the file is actually written before you append to it.

However, if it contains a lot of non-character data as your screenshots indicate, maybe you have to consider the file to be a "binary" type. In this case you should use ReadAllBytes / WriteAllBytes, split the file manually into lines (searching the byte array for \r\n) and then insert new data at the desired locations. You need to convert strings to a byte array for this purpose using Encoding.GetBytes("...") (using the right encoding).

Taking some code from another linked answer, full code for this would like:

static class MyEnumerableExtensions
{
//For a source containing N delimiters, returns exactly N+1 lists
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))
{
yield return list;
list = new List<T>();
}
else
{
list.Add(item);
}
}
yield return list;
}
}

public InsertLine()
{
byte[] bytes = File.ReadAllBytes(...);
List<List<byte>> lines = bytes.SplitOn((byte)'\n').ToList();
string lineToInsert = "Insert this";
byte[] bytesToInsert = Encoding.Default.GetBytes(lineToInsert);
lines.Insert(2, new List<byte>(bytesToInsert));
File.WriteAllBytes(..., lines.SelectMany(x => x).ToArray());
}

Insert value into a string at a certain position?

You can't modify strings; they're immutable. You can do this instead:

txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);


Related Topics



Leave a reply



Submit