Search This Blog

Wednesday, March 23, 2016

Rename files from a folder C#

C# > Files > File Class > Move


Moves a specified file to a new location.
  • option to specify a new file name

Example 

Rename files from a folder 

DirectoryInfo d = new DirectoryInfo(@"D:\folder");
FileInfo[] infos = d.GetFiles("*.*");
int i = 1;
foreach (FileInfo f in infos)
{
  File.Move(f.FullName, Path.Combine(f.DirectoryName, + i.ToString() + ".jpg"));
  i++;
}







Friday, March 11, 2016

Mock Assembly Unit Test C#

C# > Unit tests > Mock Assembly 

If you try to mock

var mock = new Mock<Assembly>();

You will get this error:

The type System.Reflection.Assembly implements ISerializable, but failed to provide a deserialization constructor

Solution

Mock _Assembly interface instead of Assembly class.


var mock = new Mock<_Assembly>();
mock.Setup(w => w.GetTypes()).Throws(new Exception());

Tuesday, March 8, 2016

yield C# Example with KeyValuePair

C# > Keywords > yield

Yield  returns each element one at a time.

When to use:

  • when calculate the next item in the list 
  • for infinite sets

Example


IEnumerable<KeyValuePair<string, string>> dataList = GetData();
dataList.ToList().ForEach(s => MessageBox.Show(s.Key + s.Value));

private IEnumerable<KeyValuePair<string, string>> GetData()
{
yield return new KeyValuePair<string, string>("1", "A");
yield return new KeyValuePair<string, string>("2", "B");
yield return new KeyValuePair<string, string>("3", "C");

}

Thursday, March 3, 2016

Concatenate list of strings c#

C#>  Enumerable > Aggregate

Aggregate performs a calculation over a sequence of values.

Example


List<string> items = new List<string>() { "1", "2", "3", "4" };

var x = items.Aggregate((a, b) => a + "," + b); // "1,2,3,4"