Editing some text in a text file in WPF - c#

I am new to using forms and C # and trying to do an assignment to create a phone book. I have different options in my phone book
To Add a contact
To show all contacts
and To edit a certain contact.
I am having trouble in how to do editing when text is stored in a text file. I have the following code for my add which adds name, phone number and email. How would i be able to edit one of the names from a list of contacts that is saved in the text file?
Add Code:
private void addButton_Click(object sender, RoutedEventArgs e)
{
TextWriter writer = new StreamWriter("D:\\class1.txt", append: true);
try
{
string Name01 = firstName.Text;
string Name02 = lastName.Text;
string Phone1 = mobile.Text;
string Phone2 = homePhone.Text;
string emailadd = email.Text;
string Informtion = Name01 + "\n" + Name02 + "\n" + Phone1 + "\n" + Phone2 + "\n" + emailadd;
writer.WriteLine("---------------");
writer.WriteLine(Informtion);
MessageBox.Show("Success!! Contact information added for: " +Name01 + " " +Name02);
}
catch (Exception ex)
{
throw ex;
}
finally
{
writer.Close();
writer.Dispose();
}
}

It appears your text file is not structured. Unstructured text is very difficult to search and edit programmatically.
Try using XML or JSON formatted text instead which will allow you to work with entries much easier, especially if you use one of the many open source libraries specifically developed to work with entries in these two formats...
Let's take this XML for example:
<?xml version="1.0" encoding="UTF-8"?>
<SnomIPPhoneDirectory>
<Title>PhoneList - Snom</Title>
<DirectoryEntry>
<Name>Friend, First</Name>
<Telephone>555-456-7890</Telephone>
</DirectoryEntry>
<DirectoryEntry>
<Name>Person, Second</Name>
<Telephone>555-654-0987</Telephone>
</DirectoryEntry>
<SoftKeyItem>
<Name>F1</Name>
<Label>Dial</Label>
<SoftKey>F_ENTER</SoftKey>
</SoftKeyItem>
</SnomIPPhoneDirectory>
Using a library or even XML functionality built into .NET framework it would be trivial to work with phone book entries in the object oriented way where you would not have to do any string parsing.

Related

Store multiple int in a .txt file, each time on a new line

Sorry for the bad title, i didn't know how to explain it better. I just started in Csharp so its probably a dumb mistake.
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = "CPU Usage" + " " + (int)cpuCounter.NextValue() + "%";
string[] usageCPUay = { label1.Text };
System.IO.File.WriteAllLines(#"C:\Users\Filip\Desktop\CPUOutput.txt", usageCPUay);
}
So this is the code I have issues with and can't understand how to fix it. I tried with streamwriter but I got the same issues. I want to make the output the cpuCounter gives to store in a txt file. But every time it just writes the latest CPU Usage and not every one. Like this wrong output. I want it to type all the cpu usages it got and store them like that but every new one in a separate line.
Let's analyze your code:
you have a method, in the body you have label1.text which is text I assume, a string.
then you have got an array of strings, but this array contains only a single element, which is label1.text, then you write in the text file the array, which contains only a single element.
3 errors I see:
1.- the array contains a single element, therefore you are only storing a single line.
2.- at the end of the string that you are meant to record in the text file you should add "\n" for a new line.
3.- I understand from https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllines?view=netcore-3.1#System_IO_File_WriteAllLines_System_String_System_String___ that it creates the file as new, therefore you may be deleting what you already have.
Solution:
Like in the example that was presented to you in the link, I would do the following:
label1.Text = "CPU Usage" + " " + (int)cpuCounter.NextValue() + "%\n";
string[] usageCPUay = { label1.Text };
if (!File.Exists(path))
{
// Create a file to write to.
File.WriteAllLines(path, usageCPUay);
}
else{
File.AppendAllText(path, usageCPUay);}

Save text to a text file already created

So I am currently trying to do this question for tafe but am having trouble getting it to add text to the file after the first time.
"Create an application that at start up asks the user to choose an output file using a Save File Dialog Window. The application to have a “Write to File” button that when clicked will take a name and age that the user has entered into two text boxes and write them directly to the file. The user can repeat the button click action as often as they wish."
This is my current code for it:
private void Form4_Load(object sender, EventArgs e)
{
saveFileDialog1.Title = ("Choose Save Location");
saveFileDialog1.ShowDialog();
}
private void btnSendToFile_Click(object sender, EventArgs e)
{
string strName = txtName.Text;
string strAge = txtAge.Text;
string strTitles = ("Name \t\t Age");
string strCombined = strTitles + "\n" + (strName + "\t\t" + strAge);
System.IO.StreamWriter OutFile;
MessageBox.Show("The Name and Age of the Person Entered Will be Written to a File");
OutFile = System.IO.File.CreateText(saveFileDialog1.FileName);
OutFile.WriteLine(strCombined);
OutFile.Close();
MessageBox.Show("The Details Have Been Written to File" + saveFileDialog1.FileName);
StreamWriter AddFile = File.AppendText(saveFileDialog1.FileName);
AddFile.Write(strCombined);
}
I'm not sure if I should be doing a loop or not and this is the form itself, https://gyazo.com/e2c4170d46295d6f92a35026e1f2304b
Any help is appreciated, Thanks in advance
For what you're doing you absolutely don't need to work with streams or anything that low level (you don't need to call the create methods on files and use a stream returned by it). You can directly use the methods that write or append to the file and handle all of this for you.
For example using AppendAllText will do everything for you (managing the streams, flushing and closing them, appending at the end, creating the file if it doesn't exist etc etc).
so you can replace all of this code :
System.IO.StreamWriter OutFile;
MessageBox.Show("The Name and Age of the Person Entered Will be Written to a File");
OutFile = System.IO.File.CreateText(saveFileDialog1.FileName);
OutFile.WriteLine(strCombined);
OutFile.Close();
MessageBox.Show("The Details Have Been Written to File" + saveFileDialog1.FileName);
with
File.AppendAllText(saveFileDialog1.FileName, strCombined);
I have no idea what you're doing in the code that follows it (calling appendtext, i assume you're thinking you need to append after creating?) in any case you don't need it. So if you just want to append all the text of "strcombined" at the end of the file each time you click the whole function should look like :
private void btnSendToFile_Click(object sender, EventArgs e)
{
string strName = txtName.Text;
string strAge = txtAge.Text;
string strTitles = ("Name \t\t Age");
string strCombined = strTitles + "\n" + (strName + "\t\t" + strAge);
MessageBox.Show("The Name and Age of the Person Entered Will be Written to a File");
File.AppendAllText(saveFileDialog1.FileName, strCombined);
MessageBox.Show("The Details Have Been Written to File" + saveFileDialog1.FileName);
}
Also as a side comment i would rewrite all of it as such for readability, these are suggestions and not hard rules:
1) Removed hungarian notation (Don't add a prefix to your variable to indicate it's type, it's generally frowned upon)
2) Removed a lot of the temporary variables that aren't really needed (used once in the same local function)
This makes for a much smaller and very readable function:
private void btnSendToFile_Click(object sender, EventArgs e)
{
MessageBox.Show("The Name and Age of the Person Entered Will be Written to a File");
File.AppendAllText(saveFileDialog1.FileName,"Name \t\t Age"+ "\n" + txtName.Text + "\t\t" + txtAge.Text);
MessageBox.Show("The Details Have Been Written to File" + saveFileDialog1.FileName);
}

Searching and Reading from file

I'm wondering if it is possible to search and read from a file and display what's in the file in a message box.
I'm wanting to search for a file by its ID, which ID is known by the user. When the user enters the ID my program opens the file which shares the same ID; eg.ID.txt in the preset folder.
when it's selected it is then read and put in a MessageBox which will then display what is in the file.
Can anyone show me how to do this?
Thanks.
//Declare variables
int TID;
private void TIDFileCreate_Click(object sender, EventArgs e)
{
StreamWriter outputFile;
outputFile = File.CreateText (TID.ToString()+".txt");
outputFile.WriteLine("Investor :" +" " + InvestorNameLabel.Text);
outputFile.WriteLine("Initial Amount" + " " +AmountLabel.Text);
outputFile.WriteLine("Date Invested" +" " +DateLabel.Text);
outputFile.WriteLine("Period Chosen" + " "+DaysInvestedLabel.Text);
outputFile.WriteLine("Rate Chosen" + " " + RateLabel.Text);
outputFile.WriteLine("Total Interest" + " " +InterestAmountLabel.Text);
outputFile.WriteLine("Transaction Number :" + " " + TransactionIDLabel.Text);
outputFile.Close();
MessageBox.Show("Transaction file for Transaction: " + TransactionIDLabel.Text + "Was Created", "Transaction File");
}
private void SearchButton_Click(object sender, EventArgs e)
{
SearchID = int.Parse(searchTextBox.Text);
string[] lines = File.ReadAllLines(#"C:\Users\Public\TestFolder\"+SearchID+".txt");
}
Can't you just use MessageBox.Show() in your SearchButton_Click method?
private void SearchButton_Click(object sender, EventArgs e)
{
SearchID = int.Parse(searchTextBox.Text);
string[] lines = File.ReadAllLines(#"C:\Users\Public\TestFolder\"+SearchID+".txt");
System.Windows.Forms.MessageBox.Show(string.Join("\r\n", lines));
}
I think that for what you want to do you should read this:
http://msdn.microsoft.com/en-us/library/ms233843.aspx
or some similar article about serialization.
This said, if the number of IDs grow in number, you should considering the adoption of a lightweight DB, i.e. SQLite, just to name one.
Take a look at the DirectoryInfo class. Something like the following should do what you want;
DirecectoryInfo dir = new DirectoryInfo(pathToRoot);
FileInfo[] files = dir.GetFiles("Id.txt"); //if using a specific name should return 1 item
TextBox.Text = File.ReadAllText(files.FirstOrDefault().FullName);
Keep in mind I have no error handling or anything here. You'll have to add that yourself, this just shows you the key classes/methods to get the files and read their contents. There are many other options like doing GetFiles(), keeping that collection in memory and then operating on them later on.

Is there a tool to find errors in Excel documents created with the OpenXML SDK?

Is there a tool that can identify the exact location of errors in an Excel document created using the OpenXML SDK?
I've created an Excel file using the Microsoft OpenXML SDK 2.5 (also tried v 2.0 with the same result), and must have made a mistake somewhere in the code. What I'm trying to find out is where.
The SDK validation functions all say the document is valid. When validating the generated Excel file using the OpenXML SDK Productivity tool, the response is "No validation error is found in the package".
But.. when opening the Excel file using MS Excel, an error alerts the user that the document needs repair, after repair the document shows up correctly. The Excel repair log says the table.xml file has an error, but not the location of the error on the file. Excel repair log follows:
Repaired Records: Table from /xl/tables/table.xml (List)
Is there a tool other than the OpenXML SDK productivity tool that can be used to validate Excel spreadsheets and identify errors in the document?
Though the post is old, but I was stuck with the same situation & so I created a windows application which shall accept the file using a file dialog & parse it to display the errors within. The first function just takes up the generated file name using the dialog box & the second methods displays all the errors that are observed within the generated file.
The generated output is as shown in the image http://s18.postimg.org/60rqf78gp/Parse_Open_XML_Generated_File.jpg
private void button1_Click(object sender, EventArgs e)
{
lblError.Text = "";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.SafeFileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
var validator = new OpenXmlValidator();
int count = 0;
foreach (ValidationErrorInfo error in validator.Validate(SpreadsheetDocument.Open(openFileDialog1.FileName, true)))
{
lblError.Text += "\r\n";
count++;
lblError.Text += ("Error Count : " + count) + "\r\n";
lblError.Text += ("Description : " + error.Description) + "\r\n";
lblError.Text += ("Path: " + error.Path.XPath) + "\r\n";
lblError.Text += ("Part: " + error.Part.Uri) + "\r\n";
}
Console.ReadKey();
}
catch (Exception ex)
{
lblError.Text += (ex.Message);
}
}

Handling XSLT file names c#

Wondering how to best deal with a problem I am having with xsltransform. Long story short, everything works in my test environment, but it crashes when I run it on the server due to the filenames it tries to deal with, which are output from another program, over which I have no control.
For example. "4Copy (2) of Fed_Around_Six__TFVC020-12.mov.xml" a simple # would solve this, but it's actually running on a service, and this service gets all files of that type in the directory and processes them one by one.
string[] filepaths = Directory.GetFiles(path, Filetype);
I keep the file name variable in:
FileInfo f = new FileInfo(filepaths[i]);
But the method I use for the transform:
myXslTransform = new XslCompiledTransform();
myXslTransform.Transform(filename,OutputFileName);
Only accepts (String, String) and thus when it sees "4Copy (2) of Fed_Around_Six__TFVC020-12.mov.xml" it has a heart attack and cuts it off.
I was thinking save the original name, rename, remove whitespace, transform, and rename back. But I think there is a smarter way to handle it out there, just not sure where to look. Is there a way of telling C# to handle a variable as a literal? Or a different transform method that accepts these weird filenames with very bad naming conventions?
Any insight that helps would be great!
The error & exception message I recieve from the Eventvwr is
Cannot Translate
\\9g031\Export\4Copy (2) of Fed_Around_Six__TFVC020-12.mov.xml
OutputName = \\9g031\Export\done\4Copy (2) of Fed_Around_Six__TFVC020-12.mov.xml
XSL LOC = C:\CXS.xsl
System.IO.IOException: The specified path is invalid.
private void PreformTranslation(FileInfo FileName, String OutputFileName , String result)
{
try
{
XslCompiledTransform myXslTransform;
myXslTransform = new XslCompiledTransform();
myXslTransform.Load(XSLname);
EventLog.WriteEntry(FileName.ToString(), OutputFileName);
myXslTransform.Transform(FileName.Name,OutputFileName);
EventLog.WriteEntry("TranslationComplete");
if (File.Exists(path + result))
{
MoveVideoFiles(path + result, outputPath + result);
}
// Rename(OutputFileName, FileName, Out);
}
catch (Exception e)
{
EventLog.WriteEntry("Cannot Translate " + FileName + " OutputName = " + OutputFileName + " \r\n"+
"XSL LOC = " + XSLname + "\r\n" + e);
}
}
The default directory when running a service is something like "windows/system32" and this isn't the directory of the executable.
This is probably the reason the XML file isn't found.

Categories