C# character counter when writing to new line
Basically I'm trying to read a really big text file and when the charecters of the line reach X amount write to a new line, but I can't seem to get the character count to work. Any help is appreciated!
using (FileStream fs = new FileStream(betaFilePath,FileMode.Open))
using (StreamReader rdr = new StreamReader(fs))
{
while (!rdr.EndOfStream)
{
string betaFileLine = rdr.ReadLine();
int stringline = 0;
if (betaFileLine.Contains("þTEMP"))
{
//sb.AppendLine(@"C:\chawkster\workfiles\New Folder\GEL_ALL_PRODUCTS_CONCORD2.DAT");
string checkline = betaFileLine.Length.ToString();
foreach (string cl in checkline)
{
stringline++;
File.AppendAllText(@"C:\chawkster\workfiles\New Folder\GEL_ALL_PRODUCTS_CONCORD3.DAT", cl);
if(stringlin开发者_运维知识库e == 1200)
{
File.AppendAllText(@"C:\chawkster\workfiles\New Folder\GEL_ALL_PRODUCTS_CONCORD3.DAT","\n");
stringline = 0;
}
}
}
}
Error:
foreach (string cl in checkline)
Error 1 Cannot convert type 'char' to 'string'
I don't understand why you have string checkline = betaFileLine.Length.ToString();
since that will just take the current line and give you the length which is a number in a string format. Don't you want all the characters in the current line? Not sure what you want the numeric length there.
Not really sure what you are doing exactly but try:
// Get the current line as an array of characters
char[] checkline = betaFileLine.ToCharArray();
// Iterate for each character add to you file?
foreach (char cl in checkline)
I would use a Regular Expression to split the input string into chunks of the desired amount of characters. Here's an example:
string input = File.ReadAllText(inputFilePath);
MatchCollection lines = Regex.Matches(input, ".{1200}", RegexOptions.Singleline); // matches any character including \n exactly 1200 times
StringBuilder output = new StringBuilder();
foreach (Match line in lines)
{
output.AppendLine(line.Value);
}
File.AppendAllText(outputFilePath, output.ToString());
System.String implements an IEnumerable - you need to use the code
foreach (char cl in checkLine)
{
...
File.AppendAllText(fileName, cl.ToString());
}
I'd also suggest you put it all into an in-memory stream or StringBuilder and persist it all to the file in one go, rather than writing each character to the FileStream separately.
精彩评论