How can I replace my txt file with an array? - c#

I made a array out of a txt file and now i want to replace the array in this txt file (replace like in update).
becouse i edited the array, and now i want to replace the txt file again , i hope its possible and i hope its possible with breaklines.
string[] linesa = File.ReadLines("file1.txt").ToArray();
this is the line where i make a array of my txt.
number = Array.IndexOf(linesa, commonElement);
number = number + 1;
email = linesa[number];
linesa[number] = "";
number = number - 1;
linesa[number] = "";
this is the edit i made and now i want to put it back in the txt file this is where i have alot of problems with.

Just use WriteAllLines method. It will replace the contents of the file if the file exists.
File.WriteAllLines("file1.txt", linesa);

Related

Importing text files lines to certain text and combo boxes

My apologies upfront if this is posted incorrectly. I will promptly take it down if requested.
I am (very much) a beginner of C# and Visual Studio. I have created a little program that exports data into a text file. See this picture:
You'll see my program, the export feature, and the exported text file.
Now I want to do the reverse and import these created text files into my program.
My first guess is to somehow call the lines (or strings). But how would I get just pieces of the line into my text fields or combo boxes? For instance, see POINT 1 in the text file and the program.
I am not posting any code because I have not written any yet as I do not know where to start. Yet, I can post any of my existing code if requested.
I will do whatever I need to make it easier for you to help. Thank you!
My first question is why you are using a combobox for a number that can supposedly go up to 123? Are there limited options for your values because if not, I would instead use textboxes.
I would start by create a Object class for "Point" accepting 6 parameters for each of the values. Then importing your text file data into your application with some sort of StreamReader or OpenFileDialog. This is some sample code that you can use/change to fit your needs (working with beginning values and Point at the beginning of your line won't work for this code).
Stream myStream;
openFileDialog1.FileName = string.Empty;
openFileDialog1.InitialDirectory = "C:\\";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (extension.Equals(".TXT", compareType))
{
try
{
using (myStream = openFileDialog1.OpenFile())
{
string path = Path.GetDirectoryName(openFileDialog1.FileName);
StreamReader reader = new StreamReader(openFileDialog1.FileName);
string line;
while ((line = reader.ReadLine()) != null)
{
string[] value = line.Split('-'); //Split line based on delimiter
_pointList.Add(new Parameter(value[0], value[1], value[2], value[3], value[4], value[5]));
}
If you want to populate your textbox, you can call each element from your list.
textbox1.Text = _pointList.ElementAt(0).Value1;
Hope this helps!
I'm not so great with comboboxes as I haven't done any winforms stuff in a while, but here's how to get your text file data into your c# program:
string[] fileEntries = Directory.GetFiles(yourPathToFileHere);
This will insert each line of your text file as a string in an array (e.g. line 1 of your textfile = fileEntries[0]. Then you're probably going to want to split the line into individual items of interest so you'll want to use this:
string[] partsOfString = yourString.Split('charToSplitOn');
See if you can solve it yourself from there. If you still need help let me know and we'll go further! : )
EDIT1: A demo of .Split() in action!
string inputString = "POINT 1 123-123-123N 123-123-123W";
string[] results = inputString.Split('-', ' '); //split the input on hyphens and spaces
your results view will look like this:
results[0] = "POINT"
results[1] = "1"
results[2] = "123"
results[3] = "123"
results[4] = "123N"
results[5] = "123"
results[6] = "123"
results[7] = "123W"

Find and replace with lookup file

I want to find and replace text in a textfile with a lookup file.
Currently i use the following code to replace a single string:
System.IO.StreamReader objReader;
objReader = new System.IO.StreamReader(someTextFile);
string content = objReader.ReadToEnd();
objReader.Close();
content = content.Replace("Text1", "Replacetext1");
System.IO.StreamWriter objWriter;
objWriter = new System.IO.StreamWriter(someTextFile);
objWriter.Write(content);
objWriter.Close();
I want to use a csv file for lookup. The format of this file is:
Text1, Replacedtext1
Text2, Replacedtext2
Text3, Replacedtext3
etc...
Who can me give some tips?
Thanks
OK Here are some tips:
1) use
string [] allLines = System.IO.File.ReadAllLines("yourLookUpFilePathHere");
it will return all lines in a string array. The same you can do with your file in which you want to make the replacements. Now you can loop through the look up file.
2) At each position / line in the array you can use the method:
string [] partsOfLine = allLines[i].Split('hereYourSeparatorAsChar');
3) now if you have fiddled out the first word you can start a second loop to look for matches in the replacement file and there you can use the line from your code:
allLinesOfReplaceFile[i] = allLinesOfReplaceFile[i].Replace("Text1", "Replacetext1");
I hope you get the drift, if it is still unclear then drop me a comment

Read text file save each line assign line number and compare

I need to compare two text files what I would like to do is read file line by line, assigning for each saved string line number compare and save differences to text file. The biggest problem is some lines such as .0091,.0671,.0105,.872 need to be split and compared invalidly. What would be the easiest way to split them and still store for each separated item same line number.
Example text file lines that contain comma will be split.
650,0
'132000/V3'
'17874/V3'
1.5
'30s'
-25,40,35
'CSL'
'EOLC'
.0776
96,13
.0091,.0671,.0105,.872
3625,1215
An initial approach could be something like this.
var lines = File.ReadAllLines(#"TextFile1.txt");
var fileMap = new Dictionary<int,string[]>();
for (int i = 0; i < lines.Length; i++)
{
fileMap.Add(i,lines[i].Split(','));
}

How to move to next file

I've searched high and low for days now to figure away to read a directory then edit a text file based off the file names in the directory with each file name replacing a text on a different line. I have came up with the code below but the problem is it changes the text on all lines to the first file name.
DirectoryInfo dinfo1 = new DirectoryInfo(path);
FileInfo[] Files1 = dinfo1.GetFiles("*.*");
string text = File.ReadAllText("path/text.txt");
foreach (FileInfo file in Files1)
{
text = text.Replace("oldtext1", "path" + file.Name);
text = text.Replace("oldtext2", "path" + file.Name);
text = text.Replace("oldtext3", "path" + file.Name);
}
File.WriteAllText("path/text.txt", text);
Note: I have 100 files in the folder and want to add all 100 files to the text in a first to last order or alphabetical order as new files will be added and I want to keep the order.
If your goal is to replace oldtext1 with the first filename and oldtext2 with the second and so forth, then this should be pretty simple:
for (var i = 0; i < Files1.Length; i++)
{
text = text.Replace("oldtext" + (i+1), "path" + Files1[i].Name);
}
We are using a regular for loop because we want to have an index into the Files1 array. Then we build the string to be replaced by concatenating oldtext with i+1 and we replace it with the current filename in the array.
So first time through the loop, we replace:
oldtext1 => filename1
the second time:
oldtext2 => filename2
and so no:
oldtextn => filenamen
Note: I have 100 files in the folder and want to add all 100 files to the text in a first to last order or alphabetical order as new files will be added and I want to keep the order.
Note that the order of files returned by DirectoryInfo.GetFiles is not guaranteed to be in any particular order. You should use Array.Sort to sort them before you run the above loop.
text.Replace("oldtext1", path + file.Name);
After this action, there will be no oldtext1 can be replaced for the next file name,same to oldtext2 and oldtext3,this is why all lines has been changed to the first file name, I think below code will help you
text += file.FullName+Environment.NewLine;

How do I retrieve the value of a string from a list of .cs files?

I have a list of .cs files, each of which contain a string commandID. I need to retrieve the value of this string.
How do I implement this search and retrieve value mechanism in C#?
//Sample code to list all .cs files within a directory
string[] filePaths = Directory.GetFiles(#"c:\MyDir\", "*.cs");
// Sample code to read 1 file.
// Read each line of the file into a string array. Each element
// of the array is one line of the file.
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\Public\TestFolder\file1.cs");
// Display the file contents by using a foreach loop.
foreach (string line in lines)
{
// INSERT YOUR SEARCH LOGIC HERE
}
I am assuming that, there is some string named CommandId in your .Cs files in your project and you are trying to get the value of it because you donot want to manually go to each file and get its value.
Follow the following
1- Paste all the .CS files in a separate folder.
2- Use FileSytem to get all the files in that folder
3- Use stream reader to get the text in the .cs files
4- compare each line in the file with the text you want to find.
5- If the string matches, the save it somewhere like XML or another text file.
6- Read the next file and Go back to step 3.
Finally got the ID out of it :)
let's say you have found the line you want, so I get the ID out of the line like :
string line = "while(i<10){CommandID = 15852; i+=1;}";
//I've put a complicated code in the string to make you sure
var rightSideOfAssignment = line.Split(new string[] {"CommandID"}, StringSplitOptions.RemoveEmptyEntries)[1];
int val = 0,temp;
bool hasAlreadyStartedFetchingNumbers= false;
foreach (char ch in rightSideOfAssignment) //iterate each charachter
{
if (int.TryParse(ch.ToString(), out temp)) //if ch is a number
{
foundFirstInteger = true;
val *= 10;
val += temp;
}
else
{
if (hasAlreadyStartedFetchingNumbers)
break;
//If you don't check this condition, it'll result to 158521
//because after hitting `;` it won't stop searching
}
}
MessageBox.Show(val.ToString()); //shows 15852

Categories

Resources