Read Two Columns From CSV File in c# - c#

With a csv file looking like this:
usernames,passwords
us1,ps1
us2,ps2
I would like all usernames in one array an all passwords in another.
Current code:
(Trying to make a login system that interacts with a database.)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Globalization;
namespace Login
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string[] usernames = new string[] { };
string[] passwords = new string[] { };
private void btnLogin_Click(object sender, EventArgs e)
{
lblLoginSucsess.Text = "";
for (int i = 0; i < Math.Min(usernames.Length, passwords.Length); i++)
{
if ((usernames[i].ToLower() == txtUsnme.Text.ToLower()) && (passwords[i].ToLower() == txtPass.Text.ToLower()))
{
lblLoginSucsess.Text = $"Welcome, {txtUsnme.Text}.";
// run calc
Process.Start("C:/Users/finch/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/HP Inc/Calculator.appref-ms");
}
}
}
}
}
If you can help, Thanks.

Instead of having two separate list, it would be better if you had a Dictionary of UserName/Password. You could read CSV and convert to dictionary by
var dataLines = File.ReadAllLines(filePath);
var userPassDictionary = dataLines.Skip(1)
.Select(x=> x.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(x=> x.First().ToLower(),v=>v.Last());
Now you could access validate the user as
if (userPassDictionary[txtUsnme.Text.ToLower()] == txtPass.Text)
{
}
Note
It was also curious to note that your were comparing password case-insensitevely. While it might depend on the business requirement, most often than not, passwords are case-sensitive. Wanted to highlight it, just in case, it was by accident.

Related

Trying to transfer files for the target user

today we were trying to transfer files with using C# but there are some problems here i don't really know what is wrong
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace FileTransfer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string curDir = Directory.GetCurrentDirectory();
var userDir = new DirectoryInfo(Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile));
string path = curDir + #"\1.jar";
string path2 = userDir + #"\Desktop\2.jar";
File.Move(path, path2);
}
}
}
It says 1.jar file cannot found.
Try this:
string path = Path.Combine(curDir,"1.jar");
string path2 = Path.Combine(userDir,"Desktop","2.jar");
//if this still doesn't work, put a breakpoint after these two lines
When your breakpoint is hit look at the value of path. Is there a even file at that location? If not, you need build your path correctly.
Also, it would be a good idea to check if the file exists before you try to move it:
if(!File.Exists(path))
{
//handle this scenario here
return;
}
File.Move(path,path2);

List comparison not working

I'm trying to make an application that reads two text files, takes the two, and merges them into one single list. Then take said list, and compare it to another list (from another text file). The problem is that no matter what I do my program always goes to else (see the line where it says
if (BoysAndGirlsList.Contains(NameEntered) && MostPopularNamesList.Contains(NameEntered))
). I don't know why it does this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Linq; //Needed for concat.
namespace Name_Search
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string BoyNames = System.IO.File.ReadAllText(#"D:\Google Drive\Course Work\C# Intro\Student Sample Programs\Chap07\BoyNames.txt"); //Reads BoyNames txt file.
List<string> BoyNamesList = BoyNames.Split('\n').ToList(); //Converts it to a list.
//BoyNamesList.ForEach(Console.WriteLine); <-Testing to make sure that the list is working properly.
string GirlNames = System.IO.File.ReadAllText(#"D:\Google Drive\Course Work\C# Intro\Student Sample Programs\Chap07\GirlNames.txt"); //Reads GirlNames txt file.
List<string> GirlNamesList = GirlNames.Split('\n').ToList(); //Converts it to a list.
List<string> BoysAndGirlsList;
BoysAndGirlsList = BoyNamesList.Concat(GirlNamesList).ToList(); //Adds the lists together.
//BoysAndGirlsList.ForEach(Console.WriteLine); <-Again just testing that the list is working.
string MostPopularNames = System.IO.File.ReadAllText(#"D:\Google Drive\Course Work\C# Intro\Student Sample Programs\Chap07\MostPopularBoyAndGirlNames.txt"); //Reads MostPopularBoyAndGirlNames txt file. Compiled from http://goo.gl/1crLcY.)
List<string> MostPopularNamesList = MostPopularNames.Split('\n').ToList(); //Converts it to a list.
string NameEntered = nameInput.Text;
if (BoysAndGirlsList.Contains(NameEntered) && MostPopularNamesList.Contains(NameEntered))
{
MessageBox.Show("This name is one the most popular names!");
}
else
{
MessageBox.Show("This is not one of the most popular names.");
}
}
}
}
What is not working properly here? I've tried putting in a break, and when I did the values looked fine to me.
The issue is probably solved as mentioned by the comments, where redundant spaces in the 'names' causes them to compare unequally. You also have an issue when you want to compare names in a case-insensitive manner.
The first issue can be solved by trimming whitespace from each name:
BoysAndGirlsList = BoysAndGirlsList.Select(name => name.Trim()).ToList();
MostPopularNamesList = MostPopularNamesList.Select(name => name.Trim()).ToList();
The second issue can be solved by using an invariant case comparer:
if (BoysAndGirlsList.Contains(NameEntered, StringComparer.InvariantCultureIgnoreCase) &&
MostPopularNamesList.Contains(NameEntered, StringComparer.InvariantCultureIgnoreCase))

C# - Prevent duplicate retrieval of posts

i'm rather new and am trying to create a C# program that retrieves post from Facebook using FB API.
I have a word count feature which checks against a negative word dictionary.
This means that it would display the negative word along with its frequency occurrence.
The problem i'm facing now is that, i want to display the posts that contains this negative words. However, if the negative word exists 3 times in the post, the post would appear thrice. How do i solve this problem?
Below is my code:
(For designer)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace empTRUST
{
public partial class PostAnalysis : Form
{
DBStatusDL ad;
string target_fbid;
public PostAnalysis(string target_fbid)
{
InitializeComponent();
this.target_fbid = target_fbid;
ad = new DBStatusDL();
}
private void button_Displayposts_Click(object sender, EventArgs e)
{
int i = 1;
var dir = new DirectoryInfo(Application.StartupPath + "\\Dictionary"); //Load the dictionary from debug folder
var ed = new matchingWordsWithPosts();
var rows = ad.LoadStatus(target_fbid); //Call the load status function based on fb_id
foreach (FileInfo file in dir.GetFiles()) //For loop, to loop through files
{
var dict = File.ReadAllLines(dir.FullName + "\\" + file);
foreach (var row in rows)
{
List<DataRow> words = ed.countWordsInStatus(row, dict); // Retrieves word dictionary returned from function
foreach (var word in words)
{
var item = new ListViewItem(new[] { i.ToString() ,word["Status_message"].ToString(), word["Status_time"].ToString() });
listViewPosts.Items.Add(item);
i++;
}
}
}
}
private void button_Back_Click(object sender, EventArgs e)
{
this.Close();
var abc = new AnalysisPage(target_fbid);
abc.Show();
}
}
}
(For class)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
namespace empTRUST
{
class matchingWordsWithPosts
{
public List<DataRow> countWordsInStatus(DataRow status, string[] dictArray)
{
List<DataRow> statusList = new List<DataRow>();
var words = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase); // local word dictionary is created here
foreach (var dictEntry in dictArray)
{
var wordPattern = new Regex(#"\w+");
string smallDictEntry = dictEntry.ToLower();
foreach (Match match in wordPattern.Matches(status["Status_message"].ToString()))
{
if (match.ToString() == smallDictEntry)
{
statusList.Add(status);
}
}
}
return statusList; // returns local word dictionary to receiving end
}
}
}
Because you didn't provide the countWordsInStatus() function, I can't know if that's the problem. However, it looks like the problem is that that function continues going through a post even if it has already matched one such word. To fix this, you could put continue; (or perhaps a break;, depending on the code you're using) after adding a post to the list you're returning. This would have the loop skip to the next post, and make sure it doesn't continue counting words in the post that has already had a match.
If you post that function, it should be much easier to understand the issue.
After a word is matched and you process the post exit the loop.

setting up filesystem permissions

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.AccessControl;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string Directoryd = "D:";
string mydirectory = Directoryd + "\\" + "rs\\";
if (!Directory.Exists(mydirectory))
{
Directory.CreateDirectory(mydirectory);
}
DirectoryInfo di = new DirectoryInfo(mydirectory);
DirectorySecurity ds = di.GetAccessControl();
ds.AddAccessRule(new FileSystemAccessRule(#"*",FileSystemRights.FullControl,AccessControlType.Allow));
di.SetAccessControl(ds);
}
}
}
this is my code when i execute this the pop up is showing that
Actually, this code is to create a folder rs and set its permission to deny full control but on running the error come with the message
Some or all identity references could not be translated.
What is the error?
You should change the following line:
ds.AddAccessRule(new FileSystemAccessRule(#"*",FileSystemRights.FullControl,AccessControlType.Allow));
to:
ds.AddAccessRule(new FileSystemAccessRule(#"Everyone",FileSystemRights.FullControl,AccessControlType.Allow));
Also if you look at the following Everyone Group there is an answer a bit further down that suggests you should use SSID's instead of the names.
Try the group "Everyone", not *.

Is there a tool that allows easy exporting of messages from a message queue (MSMQ)?

I am currently working on batch processing application using MSMQ in C#. In the application design, I have an error queue containing XML messages using the ActiveXFormatter. I know that I can write an application to write these error messages to text files or database tables.
Are there other pre-built tools available allowing you to export messages to variety of formats (i.e. text files, database tables, etc.)? I am just looking for best practices.
Ok. I found the solution of writing code to be really easy. Here's my reference solution.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Messaging;
namespace ExportMSMQMessagesToFiles
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnExportTextFiles_Click(object sender, EventArgs e)
{
//Setup MSMQ using path from user...
MessageQueue q = new MessageQueue(txtMSMQ.Text);
//Setup formatter... Whatever you want!?
q.Formatter = new ActiveXMessageFormatter();
// Loop over all messages and write them to a file... (in this case XML)
MessageEnumerator msgEnum = q.GetMessageEnumerator2();
int k = 0;
while (msgEnum.MoveNext())
{
System.Messaging.Message msg = msgEnum.Current;
string fileName = this.txtFileLocation.Text + "\\" + k + ".xml";
System.IO.File.WriteAllText(fileName, msg.Body.ToString());
k++;
}
MessageBox.Show("All done!");
}
}
}

Categories

Resources