C# Foreach Loop

25 03 2008

ok so this is a little code snippet. Lets say I have 10 text files in a folder and I want to add my ASCII signature to the end of all of them. I can put them in an array, and use a Foreach loop to do it to all of them at once. Heres how:
public static void write(String[] files)
{
foreach (String s in files)
{
FileStream fs = new FileStream(s, FileMode.Open, FileAccess.Write);
String[] line = {" ..jjLLtt \r\n",
" GGffiiGGLL \r\n",
" iiDD ,,EE,, \r\n",
" ttGG EEii \r\n",
" ;;EE.. ;;EEtt \r\n",
" LLEEffGGEEtt \r\n",
" ;;;;..KK;; \r\n",
" ;;,, ;;KK.. ;;;; \r\n",
" ..KKDD ii,,;;EEtt KKEE \r\n",
" ..LLtt LLDDDDtt LLjj \r\n"};
for (int i = 0; i < line.Length; i++)
{
Byte[] buffer = System.Text.Encoding.ASCII.GetBytes(line[i]);
try
{
fs.Write(buffer, 0, line[i].Length);
}
catch (Exception e)
{
// Do Nothing
}
}
fs.Close();
}

Now unfortunately because it gets rid of all the tabs, you can see what it actually looks like, but you can see it here

The parameter for the write method is an array of strings. The strings in this case happen to be file names. So the method will take all the filenames into it, and for each one, open them in a filestream, and using the filestream for each one, will write the ASCII signature in the file, and then close the filestream.





Boo for inefficient applications!

9 01 2008

Everyone has used one. Mostly because everyone has used Internet Explorer. But everyone has gotten one of those programs that is just slow and a total resource hog. We all know and hate them. You feel even worse, though, when you realize you have created one yourself. I was pretty happy when I posted last because I had gotten a connection between the server and the client and everything was working pretty well.

Unfortunately, now I realize that, even though it does not use a whole lot of memory, the server uses 99% of my CPU. And I have a decent CPU as well. I mean, I know why it does it but i guess i have to figure out a way around it. Heres the code snippet that I’m pretty sure causes the problems:


while (true) {
if (server.Pending()) {
server.AcceptSocket();
Console.Out.WriteLine("Connection Accepted");
}
}

As you can see, the code just creates an infinite loop that checks for connections. Unfortunately this causes it to check about 2 billion times a second. which obviously…would use all of your processors resources. I’m trying to use a timer that checks every second, but I’m having trouble implementing it in a console application. Maybe I will change the server to a GUI application. Might be easier to do a lot of things. I guess I’ll have to ponder it for a while

EDIT: The problem has been fixed! Hooray! With a little bit of help from my good friend Windy, Just putting System.Threading.Thread.Sleep(1000); at the end brought the CPU usage down to 00% :] And it even brought down the memory usage a little! Hooray!