C# Way to validate test data - c#

I'm running a test where i need to validate data from a linux file. I've defined the path of the file is located (see below). Once i cat the file to read the data contents (irm_dwge_stt_l__xxxx.csv.ovr) how can i validate the data within this file
Also where i have defined the measurementName where can i define what measurements belong within this.
public string validateMeasurement(string measurementName, string domaianName)
{
var processFilePath = "/inputs/ff/ff/actuals/" + measurementName + ".csv.ovr";
var actualItemData = Common.LinuxCommandExecutor.RunLinuxcommand("cat " + processFilePath);
return actualItemData;
}

One way of reading data in C# is to use File.Open.
Running cat and capturing the output is probably not the way to go.

This C# example from https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-read-a-text-file-one-line-at-a-time shows you how to read a file line by line.
You can then compare the file line by line to whatever data you are validating against.
Notice, this will probably only works if you are trying to validate a text file.
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(#"c:\test.txt");
while((line = file.ReadLine()) != null)
{
System.Console.WriteLine (line);
counter++;
}
file.Close();
System.Console.WriteLine("There were {0} lines.", counter);
// Suspend the screen.
System.Console.ReadLine();

Related

How to copy and paste text from one text file to another using C#? [duplicate]

This question already has answers here:
How to copy a file to another path?
(10 answers)
Closed 8 years ago.
I'm creating a C# code that is required to read a text file line by line and then copy each line onto a new text file. I was able to figure out how to read line by line, but I'm having trouble copying line by line to the new text file I created.
This is what I am using to read my original text file line by line:
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(#"c:\AnswerFile.txt");
while ((line = file.ReadLine()) != null)
{
System.Console.WriteLine(line);
counter++;
}
file.Close();
System.Console.WriteLine("There were {0} lines.", counter);
// Suspend the screen.
System.Console.ReadLine();
Any help is appreciated! Thank you
EDIT: I did not forget to write the code that copies the text onto another text file. That is the part I am having trouble with. I tried using streamwriter while specifying the directory of the file I want the text to go to, but something wasn't right. I want to create a code that literally reads line by line from one text file and copies line by line (as it reads from the initial file) to the new text file. I hope that clarifies my question.
EDIT2: Figured it out guys. Thank you for all the help! I had to call my company's security department to grant me access to write in the c drive.
int counter = 0;
string line;
try
{
// Read the file and display it line by line.
using (System.IO.StreamReader file = new System.IO.StreamReader(#"C:\\AnswerFile.txt"))
{
using (System.IO.StreamWriter fileWriter = new System.IO.StreamWriter(#"C:\outputFile.txt"))
{
while ((line = file.ReadLine()) != null)
{
System.Console.WriteLine(line);
fileWriter.WriteLine(line);
counter++;
}
}
}
System.Console.WriteLine("There were {0} lines.", counter);
// Suspend the screen.
System.Console.ReadLine();
}
catch (System.IO.IOException ex)
{
// Handle the Error Properly Here
}
Updated answer in response to comments about missing exception handling and closing of File handles in case of error.

Replace one specific line in a huge text file

I want to replace one specific line in a text file. The simplest solution would be:
public void ModifyFile(string path, int line, string targetText) {
var lines = File.ReadAllLines(path);
lines[line] = targetText;
File.WriteAllLines(path, lines);
}
The thing is, if the file is huge enough, I will get a System.OutOfMemoryException because File.ReadAllLines() tries to load the whole file in memory, instead of a line-by-line way.
I know there is another way to read a specific line with less memory cost:
var line = File.ReadLines(path).Skip(line-1).Take(1).ToString();
How can I replace over that line in the file?
I'm looking for something like FileStream.Write Method:
var writer = File.OpenWrite(path);
writer.Write(Encoding.UTF8.GetBytes(targetText),
offset, Encoding.UTF8.GetByteCount(targetText));
But it's difficult to know offset.
Is there a better way to do that?
-- UPDATE --
The temporary file solution suggested by answers works great.
At the same time, I am wondering, is there a specific case solution without creating a temporary file, if I know line is a small number (line < 100 let's say)? There must be a better solution if I want to change the 10th line in a text file having 100m lines.
You could just read the file a line at a time using streams, and copy the contents into a new file, or rename the old file with a backup name and then process with;
string line;
int couinter = 0;
// Read the file and display it line by line.
System.IO.StreamReader reader = new System.IO.StreamReader(path);
System.IO.StreamWriter writer = new System.IO.StreamWriter(new_path);
while((text = reader.ReadLine()) != null)
{
// Check for your content and replace if required here
if ( counter == line )
text = targetText;
writer.writeline(text);
counter++;
}
reader.Close();
writer.Close();
What you can do is open the FileStrem with StreamReader (which provides ReadLine method). Now read line by line and write the output to a temporary file line by line. When you are on the desired line just change the line.

Storing Data From WinForms App in .Txt file

I have a very basic C# WinForms application to generate random numbers. The code is shown below:
private static double RandomNumber(double min, double max)
{
Random random = new Random();
var next = random.NextDouble();
return min +(next * (max - min));
}
private void btnGenerate_Click(object sender, EventArgs e)
{
var maxNum = Convert.ToDouble(txbInput.Text);
var randomDec = Math.Round(RandomNumber(0, maxNum), 2);
txbResult.Text = randomDec.ToString();
}
Now what I want do be able to do is on the button click save the random number that is generated in a locally saved file, along with a timestamp.
I am fairly new to C# and have a limited knowledge on how to do this. Therefore any suggestions would be highly appreciated.
These examples show various ways to write text to a file. The first two examples use static methods on the System.IO.File class to write either a complete array of strings or a complete string to a text file. Example #3 shows how to add text to a file when you have to process each line individually before writing to the file. Examples 1-3 all overwrite all existing content in the file. Example #4 shows how to append text to an existing file.
class WriteTextFile
{
static void Main()
{
// These examples assume a "C:\Users\Public\TestFolder" folder on your machine.
// You can modify the path if necessary.
// Example #1: Write an array of strings to a file.
// Create a string array that consists of three lines.
string[] lines = { "First line", "Second line", "Third line" };
// WriteAllLines creates a file, writes a collection of strings to the file,
// and then closes the file.
System.IO.File.WriteAllLines(#"C:\Users\Public\TestFolder\WriteLines.txt", lines);
// Example #2: Write one string to a text file.
string text = "A class is the most powerful data type in C#. Like a structure, " +
"a class defines the data and behavior of the data type. ";
// WriteAllText creates a file, writes the specified string to the file,
// and then closes the file.
System.IO.File.WriteAllText(#"C:\Users\Public\TestFolder\WriteText.txt", text);
// Example #3: Write only some strings in an array to a file.
// The using statement automatically closes the stream and calls
// IDisposable.Dispose on the stream object.
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\Users\Public\TestFolder\WriteLines2.txt"))
{
foreach (string line in lines)
{
// If the line doesn't contain the word 'Second', write the line to the file.
if (!line.Contains("Second"))
{
file.WriteLine(line);
}
}
}
// Example #4: Append new text to an existing file.
// The using statement automatically closes the stream and calls
// IDisposable.Dispose on the stream object.
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\Users\Public\TestFolder\WriteLines2.txt", true))
{
file.WriteLine("Fourth line");
}
}
}
//Output (to WriteLines.txt):
// First line
// Second line
// Third line
//Output (to WriteText.txt):
// A class is the most powerful data type in C#. Like a structure, a class defines the data and behavior of the data type.
//Output to WriteLines2.txt after Example #3:
// First line
// Third line
//Output to WriteLines2.txt after Example #4:
// First line
// Third line
// Fourth line
Reference from here
add this:
// using System.IO;
string filepath = #"C:\test.txt"; //sample file name & location
using (StreamWriter writer = new StreamWriter(filepath))
{
writer.WriteLine(DateTime.Now.ToString() + " " + randomDec.ToString());
} // write your text in a string
To save your text to a file you need to use the IO namespace:
System.IO.File.AppendAllText(#"C:\Test.txt", txbResult && DateTime.Now.ToString());
This stuff show you how to write a string value to a file.
EDIT: Added the timestamp value.
From the wise words of MSDN:
// Example #2: Write one string to a text file.
string text = "A class is the most powerful data type in C#. Like a structure, " +
"a class defines the data and behavior of the data type. ";
// WriteAllText creates a file, writes the specified string to the file,
// and then closes the file.
System.IO.File.WriteAllText(#"C:\Users\Public\TestFolder\WriteText.txt", text);
Please refer to the documentation for more details and examples.
Edit:
Mine's missing the time stamp, but there are plenty of worthy answers here that add it :)
private void WriteData(double value)
{
using (var file = new System.IO.StreamWriter(#"C:\file.txt", true))
{
file.WriteLine(string.Format("{0} {1}", value, DateTime.Now));
}
}
You can see this link msdn. Get the time - DateTime.Now.

Find regex in file with StreamReader and overwrite it with StreamWriter

I am reading text file with StreamReader and doing Regex.Match to find specific info, now when I found it I want to replace it with Regex.Replace and I want to write this replacement back to the file.
this is text inside my file:
///
/// <Command Name="Press_Button" Comment="Press button" Security="Security1">
///
/// <Command Name="Create_Button" Comment="Create button" Security="Security3">
/// ... lots of other Commands
now I need to find : Security="Security3"> in Create_Button command, change it to Security="Security2"> and write it back to the file
do {
// read line by line
string ReadLine = InfoStreamReader.ReadLine();
if (ReadLine.Contains("<Command Name"))
{
// now I need to find Security1, replace it with Security2 and write back to the file
}
}
while (!InfoStreamReader.EndOfStream);
any ideas are welcome...
EDITED:
Good call was from tnw to read and write to the file line by line. Need an example.
I'd do something more like this. You can't directly write to a line in the file like you're describing there.
This doesn't use regex but accomplishes the same thing.
var fileContents = System.IO.File.ReadAllText(#"<File Path>");
fileContents = fileContents.Replace("Security1", "Security2");
System.IO.File.WriteAllText(#"<File Path>", fileContents);
Pulled pretty much directly from here: c# replace string within file
Alternatively, you could loop thru and read your file line-by-line and write it line-by-line to a new file. For each line, you could check for Security1, replace it, and then write it to the new file.
For example:
StringBuilder newFile = new StringBuilder();
string temp = "";
string[] file = File.ReadAllLines(#"<File Path>");
foreach (string line in file)
{
if (line.Contains("Security1"))
{
temp = line.Replace("Security1", "Security2");
newFile.Append(temp + "\r\n");
continue;
}
newFile.Append(line + "\r\n");
}
File.WriteAllText(#"<File Path>", newFile.ToString());
Source: how to edit a line from a text file using c#

Search and replace contents of text file based on mappings in CSV file in C#

I am new to programming and am working on a C# project that will search and replace certain words in a text file with new values. I have some code that works, but the OLD and NEW values are hardcoded right now. I would like to use an external CSV file as a configuration file so the user can add or update the OLD to NEW mappings at a later time. This is my current code with the OLD and NEW values hardcoded:
try
{
StreamReader file = new StreamReader(inputfullfilepath);
TextWriter writer = new StreamWriter(outputfile);
while ((line = file.ReadLine()) != null)
{
line = line.Replace("OLD1", "NEW1");
line = line.Replace("OLD2", "NEW2");
// etc....
writer.WriteLine(line);
}
file.Close();
File.Move(inputfullfilepath, inputfullfilepath + ".old");
writer.Close();
File.Move(outputfile, outputfilepath + #"\" + inputfilename);
MessageBox.Show("File Scrub Complete", "Success");
}
catch
{
MessageBox.Show("Error: Be sure data paths are valid.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
The code takes each line of the text file, tries to do a search/replace for all OLD to NEW mappings, then goes to the next line in the text file. The problem I am trying to wrap my head around is being able to make this list of OLD to NEW mappings dynamic based on a CSV (or XML if that would be easier?) configuration file so the user can add new search/replace keywords.
I tried to use the C# Application Settings in Visual Studio (which creates an XML configuration file) but I had a really hard time understanding how to make that work. What's the best way to do this so the values don't have to be hardcoded?
A csv file will work just fine.
I'll create a new Object which i'll call ReplaceObject
public ReplaceObject()
{
public string original;
public string updated;
//ideally you'd use getters and setters, but I'll keep it simple
}
Now we read from the csv
List<ReplaceObject> replaceList = new List<ReplaceObject>
while (reader.peek != -1)
{
string line = reader.readln();
var splitLine = line.split(',');
ReplaceObject rObject = new ReplaceObject();
rObject.original = splitLine[0];
rObject.updated = splitLine[1];
replaceList.add(rObject);
}
Now we go through the list.. and replace
string entireFile = //read all of it
foreach (ReplaceObject o in replaceList)
{
entireFile.Replace(o.original,o.updated);
}
//write it at the end
(Note that my code is missing some checks, but you should get the idea. Also you might want to use a StringBuilder)
My suggestion would be that you use the Settings.cs instead of CSV
It is very easy to use them and involves very less code
e.g. Properties.Settings.Default.Old1;
Here is a walkthrough http://msdn.microsoft.com/en-us/library/aa730869(v=vs.80).aspx
See this example showing how you can use it http://www.codeproject.com/Articles/17659/How-To-Use-the-Settings-Class-in-C

Categories