scaryguy scaryguy - 1 year ago 90
C# Question

How to create a folder using a variable name in C#?


Works great. I'm able to create the folder. BUT code below doesn't work.

using System;
using System.IO;
class iolar

public static void klasorOlustur()
Console.WriteLine("Oluşturmak istediğiniz BİRİNCİ klasörün adı?");
string a=Console.ReadLine();
Console.WriteLine("oluşturmak istediğiniz İKİNCİ klasörün adı?");
string b=Console.ReadLine();
Console.WriteLine("Klasörler oluşturuluyor.. Lütfen bekleyin...");

string klasorYolu="@\"H:\\"+a+"\"";
string klasorYolu2="\""+b+"\"";

DirectoryInfo klasorcuk=new DirectoryInfo(klasorYolu);
Console.WriteLine("İlk klasör oluşturuldu...");
DirectoryInfo klasorcuk2=klasorcuk.CreateSubdirectory(klasorYolu2);
Console.WriteLine("İkinci klasör de oluşturuldu...");



static void Main()

I get "Unhandled Exception: System.ArgumentException: Illegal characters in path." error. I've found some stuff about "path class" but I couldn't get a clear answer.

What should I do?

Answer Source
 string klasorYolu="@\"H:\\"+a+"\"";

Don't make the string content look like what you write in a C# program. This ought to look more like:

 string klasorYolu = @"H:\" + a;

Be sure to use the Path.Combine() method, it takes care of putting the backslashes in the right place.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download