»
S
I
D
E
B
A
R
«
FileStream StreamReader in C#
Nov 22nd, 2009 by admin

One way to go in a file and read the lines in C# is to use FileStream and StreamReader together, you should always use while loop instead of for loop, otherwise, you will get the error I keep getting for this is: Cannot convert type ‘char’ to ‘string’.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace testing
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string file = @"C:\Temp\New Folder\New Text Document.txt";
            using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                using(StreamReader sr = new StreamReader(fs))
                {
                    while(!sr.EndOfStream)
                    {
                       Console.WriteLine(sr.ReadLine());
                    }
                }
            }
        }
    }
}
Finding all factors of a given number in C#
Nov 22nd, 2009 by admin

To find all factors of a given number in C# can be done using many different ways. A lean way of doing so is:

  • Loop from 1 to the square root of the number, call the index “i”.
  • if number mod i is 0, add i and number / i to the list of factors.
public List<int> Factor(int number) {
    List<int> factors = new List<int>();
    int max = (int)Math.Sqrt(number);  //round down
    for(int factor = 1; factor <= max; ++factor) { //test from 1 to the square root, or the int below it, inclusive.
        if(number % factor == 0) {
            factors.add(factor);
            if(factor != max) { // Don't add the square root twice!  Thanks Jon
                factors.add(number/factor);
            }
        }
    }
    return factors;
}

There are many other ways you could explore. You could implement this as an IEnumerable<int> as well – use yield instead of adding to a list. The advantage with List<int> is that it could be sorted before return if required. Then again, you could get a sorted enumerator with a hybrid approach, yielding the first factor and storing the second one in each iteration of the loop, then yielding each value that was stored in reverse order.

You will also want to do something to handle the case where a negative number passed into the function.

Changing Windows shell environment variables from C++
Nov 21st, 2009 by admin

A common technique to change Windows shell environment variables from C++ is the write an env file, that is then “called” from the script.

del env.var
foo.exe ## writes to env.var
call env.var