Avoid apostrophe with regex with event or saving to file - c#

How to avoid writing into the richTextBox of saving into the file for apostrophe " ’ " and " ' "
I also tried replace:
string text = File.ReadAllText(path);
text = text.Replace("’", "").Replace("'", "");
File.WriteAllText(path, text.ToLower());
But If file content is large program hangs with using in events. Also I have this � instead delete time after time.
So would be good to avoid writing of marks with writing or with saving into the file
Seems like I'm doing it wrong:
string toFile = String.Join(" ", richTextBox1.Lines);
var pat1 = #"\s?(’|')\s?";
var out1 = Regex.Replace(toFile, pat1, "");
File.WriteAllText(path, out1.ToLower());
so this way i lost lines if text is pasted and got whole text in one string.
but want get this result, if insert is:
Could’ve
Couldn’t
Didn’t
Doesn’t
I want write it to the file like this:
couldve
couldnt
didnt
doesnt

Try this:
System.Windows.Forms.OpenFileDialog oFile = new System.Windows.Forms.OpenFileDialog();
oFile.InitialDirectory = "c:\\" ;
oFile.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
oFile.FilterIndex = 2 ;
oFile.RestoreDirectory = true ;
if(oFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string file = oFile.Filename;
string tmp = file + ".tmp";
if (System.IO.File.Exists(tmp))
System.IO.File.Delete(tmp);
using(System.IO.StreamReader sr = new System.IO.StreamReader(file))
using(System.IO.StreamWriter sw = new System.IO.StreamWriter(tmp, false, Encoding.ASCII ))
{
string line = null;
while((line = sr.ReadLine()) != null)
sw.WriteLine(line.Replace("’", "").Replace("'", ""));
}
System.IO.File.Delete(file);
System.IO.File.Move(tmp, file);
}

Related

Open txt file and replace text in the first two lines (C#)

I am writing this program that allows me to generate txt files that with an incremental number, however, i want each file serial number to be writting inside the txt file itself.
For example:
I generated 3 files, Mytext-000001.txt, Mytext-000002.txt, Mytext-000003.txt, and each file first line contains "Hello 000000" and the second line contains "My number is 000000", now i want to change each txt file to contain "Hello " + the incremental number that it is named with.
So the output of each file will be:
Mytext-000001.txt,
Hello 000001
My number is 000001
Mytext-000002.txt,
Hello 000002
My number is 000002
Mytext-000003.txt,
Hello 000002
My number is 000003
My Code
string path = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + #"\path.txt";
string pth_input = null;
string pth_output = null;
using (StreamReader sx = File.OpenText(path))
{
pth_input = sx.ReadLine();
pth_output = sx.ReadLine();
}
Console.WriteLine("Number of Files?");
string number_of_files = Console.ReadLine();
int get_number_of_files = Int32.Parse(number_of_files) + 1;
string PathFiletoCopy = pth_input;
string Extension = System.IO.Path.GetExtension(PathFiletoCopy);
string PartialNewPathFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(PathFiletoCopy), System.IO.Path.GetFileNameWithoutExtension(PathFiletoCopy) + "-");
for (int i = 1; i < get_number_of_files; i++)
{
System.IO.File.Copy(PathFiletoCopy, PartialNewPathFile + i.ToString("D6") + Extension);
}
string[] txtfiles = Directory.GetFiles(pth_output, "*.txt");
foreach (var file in txtfiles)
{
string get_file_counter = System.IO.Path.GetDirectoryName(file.Substring(7,6));
FileStream fs = new FileStream(file, FileMode.Append, FileAccess.Write);
FileStream fi = new FileStream(file, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fi))
{
using (StreamWriter writer = new StreamWriter(fs))
{
string line = null;
while ((line = reader.ReadLine()) != null)
{
string replace_line_one = line.Replace("Hello 000001","Hello"+ "["+get_file_counter+"]");
string replace_line_two = line.Replace("My number is 000001", "My number is" + "[" + get_file_counter + "]");
}
writer.Close();
} reader.Close();
}
}
Console.Read();
I hope you can help
Appreciate your help guys
string[] files = Directory.GetFiles(directoryPath, "*.txt");
Regex regex = new Regex("\\d+(?=\\.txt)");
foreach (var file in files)
{
string[] lines = File.ReadAllLines(file);
string number = regex.Match(Path.GetFileName(file)).Value;
lines[0] = "Hello " + number;
lines[1] = "My number is " + number;
File.WriteAllLines(file, lines);
}
Regex makes this solution nonspecific.
This might do the trick for you
System.IO.Directory myDir = pth_output;
int count = (myDir.GetFiles().Length) + 1;
string thenumber = String.Format("0:000000", count);
string filename = "Mytext-" + thenumber + ".txt";
string filetext = "Hello " + thenumber + Environment.NewLine + "My number is " + thenumber;
File.WriteAllText(Path.Combine(myDir,filename) , createText);
In myDir I am expecting you can pull the path of the folder which contains all the txt files.
myDir.GetFiles().Length will give you the count of the files exists in the folder and as we want only txt files you can search it like Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories).Length; instead
String.Format("0:000000", count); will give you the number in your format of preceding zeros.

SSIS remove carriage returns

I've a flat file which has 48 columns. The columns are tab delimited and the rows CR-LF (return).
Now I've the problem that there is a column which sometimes contains carriage returns and there is no possibility to change the file before the import process.
At the moment I wrote a C# script task which looks in every row, counts the tabs and when there is a return and the counted tabs are not divisible by 48 it deletes the return. This way works but it's to slow because my files are very big and with that way I've to read every character in the file.
Does someone knows a better way to get rid of these carriage returns?
Cheers!
https://community.spiceworks.com/topic/2130093-ssis-package-flat-file-destination-blank-row-at-end-of-file
public void Main()
{
string filename = #"C:\Temp\Gerard.txt";
string fileinfo = "";
string curline = "";
TextReader tr = new StreamReader(filename);
while ((curline = tr.ReadLine()) != null)
{
if (fileinfo != "")
{
fileinfo = fileinfo + Environment.NewLine;
}
fileinfo = fileinfo + curline;
}
tr.Close();
TextWriter tw = new StreamWriter(filename, false);
tw.Write(fileinfo);
tw.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}

C# unique file naming with String from Streamreader

ok i have solved my problem of finding a unique word within the file that is then used as the newly created .txt file name.
for example: current.txt files have 200 lines of words/data per file but one of the words is unique("92222225") with every current.txt file.
so the newly created output files from streamwriter becomes 92222225.txt, 933333334.txt and so on.
the whole time i though what i needed was within streamreader or streamwriter.
but what i need to add to the two was "Regex.Match".
here is the code i figured out to use for pulling strings out of a .txt file to use as a name for the output files. also to add other words to the new output file.
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\reporting";
foreach (string txtName in Directory.EnumerateFiles(mydocpath, "*.txt"))
{
StringBuilder sb = new StringBuilder();
StreamReader sr = new StreamReader(txtName);
string content = sr.ReadToEnd();
sb.AppendLine(txtName.ToString());
sb.AppendLine("= = = = = =");
sb.Append(content);
if (content.Contains("helloworld"))
{
sb.AppendLine();
sb.AppendLine("byeworld");
}
sb.AppendLine();
sb.AppendLine();
//string fileName = content.Contains("helloworld").ToString();
string FindMatch = content;
Match match = Regex.Match(FindMatch, #"9(([A-Za-z0-9\-])\d+)");
if (match.Success)
{
//this is what adds unique word as 922225.txt file name.
string capture = match.Groups[1].Captures[0].Value;
using (StreamWriter outfile = new StreamWriter(mydocpath + #"\" + capture + ".txt"))
{
outfile.Write(sb.ToString());
}
}
}
i updated this whole post so if anyone else may need this.
never even used Regex.Match before, nor knew about it or maybe i forgot about it.
If you want to name your output file use:
using (StreamWriter outfile = new StreamWriter(mydocpath + #"\901232lOi.txt"))

Read last empty line of a text file

I have funny problem - I tried several scripts that will read text files, and that's ok.
Problem occur when text file have empty line at the end - that line is "ignored".
Code I use is "usual" code for file read, like next one:
string fullFileName;
fullFileName = "myFile.txt";
var lines = File.ReadAllLines(fullFileName);
string fileContent = null;
bool firstLine = true;
foreach (var line in lines) {
if (firstLine != true)
{
//textBox1.Text += System.Environment.NewLine;
fileContent += System.Environment.NewLine;
}
else
{
firstLine = false;
}
//textBox1.Text += line;
fileContent += line;
}
textBox1.Text = fileContent;
So, if last line of file myFile.txt is empty, it is not showed in a TextBox.
Can you help me where is a problem?
I think you could avoid the loop altogether and just do:
textBox1.Text = File.ReadAllText(fullFileName);
This will preserve all the newlines.
It is a problem with the file representation, not with ReadAllLines.
See this thread: http://www.pcreview.co.uk/forums/file-readalllines-doesnt-read-last-blank-line-weird-t3765200.html
Other solution:
using (FileStream fileStream = File.OpenRead("C:\myFile.txt"))
using (StreamReader streamReader = new StreamReader(fileStream))
{
string fileContent = streamReader.ReadToEnd();
textBox1.Text = fileContent;
}
File.ReadAllLines(fullFileName);
does not reads carriage return ('\r'). i think your last line contains only carriage return thats why its not being read. put space in last line to check.
http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx

How to Get File Size,File Name,File Ext In C# Windows?

im new to c#.net,any one let me know How to Get File Size,File Name,File Ext In C# Windows.
im using open file dialog in c#..im getting only the path..i dont know how to get the file name and size..
my code is :
openFileDialog1.ShowDialog();
openFileDialog1.Title = "Select The File";
openFileDialog1.InitialDirectory = "C:";
openFileDialog1.Multiselect = false;
openFileDialog1.CheckFileExists = false;
if (openFileDialog1.FileName != "")
{
txtfilepath1.Text = openFileDialog1.FileName;
var fileInfo = new FileInfo(openFileDialog1.FileName);
lblfilesize1.Text = Convert.ToString(openFileDialog1.FileName.Length);
lblfilesize=
lblfilename=
}
Size FileInfo.Length
Name FileInfo.Name
Extension FileInfo.Extension
You don't need to use any other class. You're already using FileInfo.
You can use FileInfo Class. File Info
using System;
using System.IO;
class Program
{
static void Main()
{
// The name of the file
const string fileName = "test.txt";
// Create new FileInfo object and get the Length.
FileInfo f = new FileInfo(fileName);
long s1 = f.Length;
// Change something with the file. Just for demo.
File.AppendAllText(fileName, " More characters.");
// Create another FileInfo object and get the Length.
FileInfo f2 = new FileInfo(fileName);
long s2 = f2.Length;
// Print out the length of the file before and after.
Console.WriteLine("Before and after: " + s1.ToString() +
" " + s2.ToString());
// Get the difference between the two sizes.
long change = s2 - s1;
Console.WriteLine("Size increase: " + change.ToString());
}
}
For Extension You can use Path.GetExtension()
http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx

Categories