Argument Out of range Exception when insert element into list - c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> ul = new List<string>();
Process[] procs = Process.GetProcesses();
int u = 0;
foreach (Process proc in procs)
{
ul[u] = proc.ProcessName;
u++;
}
}
}
}
I want to move each process name into my arraylist each time loop executed but i'm getting outofbound Exception. please provide some sample codes. thanks in advance...

You can't access an element in List that hasn't been set yet. Use the .Add() function.
foreach (Process proc in procs)
{
ul.Add(proc.ProcessName);
}

Try using the .Add() function, like this:
static void Main(string[] args)
{
List<string> ul = new List<string>();
foreach (Process proc in Process.GetProcesses())
{
ul.Add(proc.ProcessName);
}
}
A List<> when created, has a default size, and in your code elements get added until that size is full (at which point the next 'insert' fails. The add() method checks to see if this size limit is no longer enough and increases the size of the list when required.
This code also eliminates the need for a couple of your variables.

Related

inserting into index location of a text file if a string does exist inside the line, if the string doesn't exist, still write line as it was

The program is supposed to look for a string in a line, and if it finds the string, it will make the inserts after meeting the condition inside the textfile. Currently, when I run this program it is now simply giving me a blank console. Previously, I had it just reading all the lines properly and could make inserts only if I remove them first but it messed the indexing up and ultimately did not give me the result I wanted. The logic is fairly straightforward, if you see any problems please share your thoughts. Please and thanks. I am very confused why this is having problems and not working.
using System.IO;
using System.Globalization;
using System.Diagnostics;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
namespace Masker
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine();
string path = #"\file1.txt";
ReadLines(path)
}
public static void ReadLines(string path)
{
int counter = 0;
var text = new StringBuilder();
foreach (string s in File.ReadAllLines(path))
{
counter += 1;
if (s.Contains("000INDEX"))
{
text.AppendLine(s.Insert(60, "#"));
}
else if (s.Contains("001PRTBNR"))
{
text.AppendLine(s.Insert(60, "#").Insert(119,"#").Insert(120,"#").Insert(121, "#"));
};
text.AppendLine(s);
//Console.Write(text.ToString());
}
Console.Write(text.ToString());
}
}
}
The last two blocks of your if/else statement will never be executed.
If the execution reaches the third check
else if (s.Contains("000INDEX"))
that will always be true. Because if it wasn't, then the first check
if (!s.Contains("000INDEX"))
would have already been true.
But the biggest problem is that if the line contains "000INDEX", your while loop becomes and infinite loop. You never leave it. That is probably the reason why you end up with a blank console.

Super-simple linq query still doesn't work

Trying to use Linq and the Entity Framework to make a super-simple lists database. The query runs, but it does not return the data I enter into it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
using static System.Console;
namespace CheckList
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Building the list.");
using (var db = new ListContext())
{
ListItem socks = new ListItem() { Title = "Get Socks" };
db.ListItems.Add(socks);
Here is the actual query:
var queryresults = from item in db.ListItems
orderby item.Title
select item;
But the foreach loop doesn't print out anything:
WriteLine("Printing out the list:");
foreach (var item in queryresults)
{
WriteLine("Item's name:");
WriteLine(item.Title);
}
The rest:
}
WriteLine("All done.");
Console.Read();
}
}
}
I've tried to simplify as much as possible, but I cannot seem to get the results to show up. What is my mistake here?
Before the query try to save changes.
db.SaveChanges();

Why the loop is taking so long and so slow?

I created a new class for the testing:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenHardwareMonitor.Hardware;
using System.Diagnostics;
using DannyGeneral;
using System.Windows.Forms;
using System.Threading;
using System.Management;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
namespace HardwareMonitoring
{
class CpuUsages
{
public static string processes;
public static string cputest()
{
PerformanceCounter cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
var unused = cpuCounter.NextValue(); // first call will always return 0
System.Threading.Thread.Sleep(1000); // wait a second, then try again
//Console.WriteLine("Cpu usage: " + cpuCounter.NextValue() + "%");
processes = "Cpu usage: " + cpuCounter.NextValue() + "%";
return processes;
}
}
}
Then in form1 i added a new timer set it to 1000ms enable it when running the program and inside the timer tick event i did:
private void timer3_Tick(object sender, EventArgs e)
{
Process[] processes = Process.GetProcesses();
foreach (Process process in processes)
{
CpuUsages.cputest();
cpuusage = CpuUsages.processes;
label26.Text = cpuusage;
}
}
This way it's working very slow take a long time to make the loop foreach.
In general i wanted to loop over each running process and get it's cpuusage.
But if i remove the foreach loop like this:
private void timer3_Tick(object sender, EventArgs e)
{
Process[] processes = Process.GetProcesses();
CpuUsages.cputest();
cpuusage = CpuUsages.processes;
label26.Text = cpuusage;
}
Then it will work fast i will see in label26 the cpuusage updating eavery second.
The problem is that it will show the cpuusage for only on process.
What can i do to solve it ?
In general i wanted to create automatic number of labels for each process in the list and display each process cpuusage. But it's so slow and take so long when i use the foreach loop.
Is there any way to solve it ?
This:
foreach (Process process in processes)
{
CpuUsages.cputest();
cpuusage = CpuUsages.processes;
label26.Text = cpuusage;
}
will make your program sleeps for 1 second * (number of processes running on your machine). No wonder the foreach loop is slow.
Remove those Sleep calls, and have your loop running in another Thread, avoiding slowing down the User interface.
Also I don't see why you are iterating over the processes returned by Process.GetProcesses() : you are not using them.

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.

C# how to convert File.ReadLines into string array?

The question that I have is regarding converting the process of reading lines from a text file into an array instead of just reading it.
The error in my codes appear at string[] lines = File.ReadLines("c:\\file.txt"); with cannot implicitly convert....
Can someone please advise on the codes to save the results in an array format? I've placed the ReadAllLines code which is able to save the results in an array too. Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace Testing
{
class Analysis
{
static void Main()
{
string[] lines = File.ReadLines("c:\\file.txt");
foreach (string r in lines)
{
Console.WriteLine("-- {0}", r);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
}
ReadAllLines Codes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace Testing
{
class ReadFromFile
{
static void Main()
{
string[] lines = System.IO.File.ReadAllLines
(#"C:\Users\Public\TestFolder\WriteLines2.txt");
System.Console.WriteLine("Contents of writeLines2.txt =:");
foreach (string line in lines)
{
Console.WriteLine("\t" + line);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
}
File.ReadLines() returns an object of type System.Collections.Generic.IEnumerable<String>
File.ReadAllLines() returns an array of strings.
If you want to use an array of strings you need to call the correct function.
You could use Jim solution, just use ReadAllLines() or you could change your return type.
This would also work:
System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("c:\\file.txt");
You can use any generic collection which implements IEnumerable, such as IList<String>.
string[] lines = File.ReadLines("c:\\file.txt").ToArray();
Although one wonders why you'll want to do that when ReadAllLines works just fine.
Or perhaps you just want to enumerate with the return value of File.ReadLines:
var lines = File.ReadLines("c:\\file.txt");
foreach (var line in lines)
{
Console.WriteLine("\t" + line);
}
Change string[] lines = File.ReadLines("c:\\file.txt"); to IEnumerable<string> lines = File.ReadLines("c:\\file.txt");
The rest of your code should work fine.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace FileReader
{
class Program
{
static void Main(string[] args)
{
var lines = File.ReadAllLines("D:/Text.txt").ToList();
if(lines != null && lines.Count > 0)
{
foreach(var line in lines)
{
Console.WriteLine(line);
}
}
Console.ReadKey();
}
}
}

Categories

Resources