double linked lists and filling - c#

I am working on a Data Structures project and have made a telephone directory. It is a windows form app. There are 2 parts of it; one is the home directory and other is the organization directory.
The home directory uses queues to take first and last name and number of the contact and saves it to a .txt file.
The organization directory uses double linked list to perform same operation and save organization name and number to a new node and then to a .txt file.
Now the problem is that though it saves to the .txt file (linked list) i am unable to search and delete that element from file as well as the linked list. I have tried everything and searched tons of websites but to no use...please help i just have two days to submit my project ;(
this is my code to insert data to doubly linked list and save to file behind the insert buttone
linked_list l;
string data;
bool check = true;
private void button1_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(textBox1.Text);
string name = textBox2.Text;
string phone = textBox3.Text;
try
{
data = "";
if (check)
{
if (comboBox1.Text == "First")
{
l.InsertFirst(id, name, phone);
data = label1.Text + ":" + textBox1.Text + Environment.NewLine + label2.Text + ":" + textBox2.Text + Environment.NewLine + label3.Text + ":" + textBox3.Text + Environment.NewLine+Environment.NewLine;
File.AppendAllText("Organization Directory.txt", data);
MessageBox.Show("DATA SAVED");
}
else if (comboBox1.Text == "Last")
{
l.InsertLast(id, name, phone);
data = label1.Text + ":" + textBox1.Text + Environment.NewLine + label2.Text + ":" + textBox2.Text + Environment.NewLine + label3.Text + ":" + textBox3.Text + Environment.NewLine+Environment.NewLine;
File.AppendAllText("Organization Directory.txt", data);
MessageBox.Show("DATA SAVED");
}
} display();
}
catch (Exception ex)
{
MessageBox.Show(ex.Source);
}
}
public void display()
{
listBox1.Items.Clear();
Nodes n = l.head;
while (n != null)
{
listBox1.Items.Add(label1.Text + ":" + n.id).ToString();
listBox1.Items.Add(n.name).ToString();
listBox1.Items.Add(label3.Text + ":" + n.phone).ToString();
listBox1.Items.Add(Environment.NewLine).ToString();
n = n.next;
}
}

Related

c# To verify excel file is damaged or not , if damaged then pop out a message box

I am a new to c# and i am doing a window form program that to check the excel file is exist or not. If exists then need to verify the excel file is damaged or not , but i have no idea how to write the code . the part of searching excel file i had done .
#
int point = 0;
if (File.Exists(path1[0]))
{
MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Tranfser Error");
point = 1;
}
else
{
for (int x = 1; x < path1.Length; x++)
{
if (File.Exists(path1[x]))
{
MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Transfer Error");
point = 1;
}
}
}
if (File.Exists(path2[0]))
{
MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Transfer Successful");
point = 1;
}
else
{
for (int x = 1; x < path2.Length; x++)
{
if (File.Exists(path2[x]))
{
MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Transfer Successful");
point = 1;
}
}
}
if (File.Exists(path3))
{
MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Havent Transfer");
point = 1;
}
if (point == 0)
{
MessageBox.Show("No File of the date "+ Year +"-"+ Month +"-"+ Day);
}
Looks like you need to check multiple paths for existence and file format? if so please construct your code better way. However the below function shall give you expected result. This uses EPPlus library, install it through nuget.
enum ExcelFileTestResult
{
FileNotFound,
ValidFormat, //File found, valid excel
InvalidFormat //File found but not valid excel
}
public static ExcelFileTestResult CheckExcelFile(string path)
{
ExcelFileTestResult result = ExcelFileTestResult.FileNotFound;
if (File.Exists(path))
{
FileInfo fi = new FileInfo(path);
try
{
// Trying to read file using EPPlus
// if the file is not valid format, it will throw error
using (ExcelPackage p = new ExcelPackage(fi))
{
result = ExcelFileTestResult.ValidFormat;
}
}
catch (InvalidDataException ex)
{
result = ExcelFileTestResult.InvalidFormat;
}
}
return result;
}
Note: EPPlus works only for xlsx, not xls.
https://github.com/JanKallman/EPPlus

C# How to check a Listbox for a string + object?

I'm trying to search for a certain number(object) in a listbox which comes together with a string in order to highlight it. In the following bit of code i override a ToString() method to contain all my objects.
public override string ToString()
{
string reservatiestring;
reservatiestring = "Kamer: " + roomNumber + "" + " Op datum: " + datum + " Aantal personen: " + personen.Count + " Naam: " + reservatienaam;
return reservatiestring;
}
Following this I add it to my listbox in the following bit of code:
listBox1.Items.Add(reservatie.ToString());
I now want to search for all the items in my listbox containing the same roomNumber object. To do this i tried the Contains() method with the text before it: "Kamer: " and the object which I'm looking for +comboBox1.SelectedItem. This however always fails and my code goes to the else option giving me the error message.
private void buttonSearch_Click(object sender, EventArgs e)
{
listBox1.SelectionMode = SelectionMode.MultiExtended;
Reservations reservaties = new Reservations();
reservaties.roomnumberstring = "Kamer: " + comboBox1.SelectedValue;
for (int i = listBox1.Items.Count - 1; i >= 0; i--)
{
if (listBox1.Items[i].ToString().ToLower().Contains(("Kamer: " + comboBox1.SelectedValue)))
{
listBox1.SetSelected(i, true);
}
else
{
MessageBox.Show("error");
}
Please note: All my roomNumber objects are stored in the combobox, so whenever i select for example roomNumber 3 in my combobox and hit search all the items in the listbox containing "Kamer: 3" should be selected.
The roomnumberstring is a option I tried which did not work unfortunately.
reservaties.roomnumberstring = "Kamer: " + comboBox1.SelectedValue;
Your override of the ToString method is wrong and won't modify anything. Try this :
public override string ToString(this string reservatiestring)
{
reservatiestring = "Kamer: " + roomNumber + "" + " Op datum: " + datum + " Aantal personen: " + personen.Count + " Naam: " + reservatienaam;
return reservatiestring;
}
I can see one thing that might make your code fail. you are comparing
.ToLower()
with "Kamer", where the "K" isnĀ“t in lowercase

Permissions on a folder

I have been looking for some time now and have not been able to find this. How can I set my program up to write or update a file from multiple users but only one group is allowed to open the read what is in the folder?
class Log_File
{
string LogFileDirectory = #"\\server\boiseit$\TechDocs\Headset Tracker\Weekly Charges\Log\Log Files";
string PathToXMLFile = #"\\server\boiseit$\scripts\Mikes Projects\Headset-tracker\config\Config.xml";
string AdditionToLogFile = #"\Who.Did.It_" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Year + ".txt";
XML XMLFile = new XML();
public void ConfigCheck()
{
if (!File.Exists(PathToXMLFile))
{
XMLFile.writeToXML(PathToXMLFile, LogFileDirectory + AdditionToLogFile);
}
}
public void CreateLogFile()
{
if (Directory.GetFiles(LogFileDirectory).Count() == 0)
{
XMLFile.writeToXML(PathToXMLFile, LogFileDirectory + AdditionToLogFile);
CreateFileOrAppend("");
}
else if (!File.Exists(XMLFile.readingXML(PathToXMLFile)))
{
XMLFile.writeToXML(PathToXMLFile, LogFileDirectory + AdditionToLogFile);
CreateFileOrAppend("");
}
else
{
FileInfo dateOfLastLogFile = new FileInfo(XMLFile.readingXML(PathToXMLFile));
DateTime dateOfCreation = dateOfLastLogFile.CreationTime;
if (dateOfLastLogFile.CreationTime <= DateTime.Now.AddMonths(-1))
{
XMLFile.writeToXML(PathToXMLFile, LogFileDirectory + AdditionToLogFile);
CreateFileOrAppend("");
}
}
}
public void CreateFileOrAppend(string whoDidIt)
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetStore((IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly | IsolatedStorageScope.User), null, null))
{
using (StreamWriter myWriter = new StreamWriter(XMLFile.readingXML(PathToXMLFile), true))
{
if (whoDidIt == "")
{
}
else
{
myWriter.WriteLine(whoDidIt);
}
}
}
}
This is my path where it needs to go. I have the special permission to open and write to the folder but my co workers do not. I am not allow to let them have this permission.
If I where to set up a database how would i change this code
LoggedFile.CreateFileOrAppend(Environment.UserName.ToUpper() + "-" + Environment.NewLine + "Replacement Headset To: " + AgentName + Environment.NewLine + "Old Headset Number: " + myDatabase.oldNumber + Environment.NewLine + "New Headset Number: " + HSNumber + Environment.NewLine + "Date: " + DateTime.Now.ToShortDateString() + Environment.NewLine);
I need it to pull current user, the agents name that is being affected the old headset and the new headset, and the time it took place.
While you create file, you have to set access rules to achieve your requirements. .
File.SetAccessControl(string,FileSecurity)
The below link has example
https://msdn.microsoft.com/en-us/library/system.io.file.setaccesscontrol(v=vs.110).aspx
Also the "FileSecurity" class object, which is an input parameter, has functions to set access rules, including group level control.
Below link has example
https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesecurity(v=vs.110).aspx
This question will be opened under a new question since I am going to take a different route for recording the data I need Thank you all for the help

Putting certain lines of a textfile into an editable listbox

So I want to put certain lines into a text box, say I use the "Search Function" to search transaction ID, it would look through the transactions.txt file and find the transaction ID and Read the 6 lines under it which show the transactions Details, once found this would then go to a the listbox which then you could edit the transaction.
I was wondering would you use loops and arrays to do this, and could someone show me how, Thank you!
Heres my current code:
//Creates a textfile with details of the transaction
public void CreateFile()
{
StreamWriter outputFile;
outputFile = File.AppendText("Transactions.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");
}
//puts all transactions in listbox
//needs to be able to find certain transactions
private void button1_Click(object sender, EventArgs e)
{
using (StreamReader sr = new StreamReader("transactions.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
}
}
Try This:
string ID = "23";
bool idFound=false;
int count = 0;
foreach (var line in File.ReadLines("transactions.txt"))
{
if (idFound && count < 6)
{
listBox1.Items.Add(line);
count++;
}
if(line.Contains(ID))//if you wantto match exactly use if(line.Equals(ID))
{
idFound = true;
}
}

C# File only copies once

With my filesystemwatcher I check when a file needs to be copied to a 2nd directory. Everytime. So for example I put in test.txt in dir1 and it automatically copies or cuts the file to dir2. Now when I put in test2.txt in dir1, nothing happens. Why is nothing happening the 2nd time?
Edit: It's a Windows Service
Here is my code:
private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
{
variable_reset();
cut_copy = ConfigurationManager.AppSettings[#"cut"];
logger("File created> " + e.FullPath + " -Date:" + DateTime.Now);
filepath = Path.Combine(source, e.Name);
name = Path.GetFileNameWithoutExtension(filepath);
extension = Path.GetExtension(e.FullPath);
size = e.Name.Length;
strSelectCmd = "INSERT INTO files (name,size,last_edit,extension) VALUES('" + name + "','" + size + "',now(),'" + extension + "')";
readquery = "select * from files where name='" + name + "'";
Mysql();
postgresql();
Record();
if (string.IsNullOrEmpty(filename) == false)
{
if (Directory.Exists(e.FullPath))
{
copyfolder();
Directory.CreateDirectory(target);
}
else
{
if (WaitForFileAvailable(e.FullPath, TimeSpan.FromSeconds(10)))
{
var file = Path.Combine(source, e.Name);
var copy_file = Path.Combine(target, e.Name);
var destination = Path.Combine(target, Path.ChangeExtension(source, Path.GetExtension(source)));
if ((String.Compare(cut_copy, "cut"))==0)
{
if (File.Exists(file))// Check to see if the file exists.
{ //If it does delete the file in the target and copy the one from the source to the target.
File.Delete(copy_file);
}
File.Move(e.FullPath, Path.Combine(target, e.Name));
}
if ((String.Compare(cut_copy, "copy"))==0)
{
if (File.Exists(file))// Check to see if the file exists.
{ //If it does delete the file in the target and copy the one from the source to the target.
File.Delete(copy_file);
}
File.Copy(e.FullPath, Path.Combine(target, e.Name));
}
}
else // The file failed to become available within 10 seconds.
{
logger("Copy has failed reason: File is being used by another program");
}
}
}
else
{
query = "INSERT INTO files (name,size,last_edit,extension) VALUES('" + name + "','" + size + "',now(),'" + extension + "')";
Mysql();
}
}

Categories

Resources