public static void CreateFolder()
{
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); //Gets desktop folder
string pathTo = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/" + "SYS_" + Random6CharString() + "/"; //Creates random directories
foreach(char path in Random6CharString())
{
System.IO.Directory.CreateDirectory(pathTo); //Method to create folders on Desktop
}
}
public static string Random6CharString()
{
string path = Path.GetRandomFileName();
path = path.Replace(".", ""); // Remove period.
return path.Substring(0, 6); // Return 6 character string
}
I'm making a game, and it should write folders to the users desktop to use as events on the game. When I get to a point, where 2 folders should be created simultaneously, it only creates one folder. Can anyone tell me how to make more than 1 folder at once? Or at least do them one after another instead of simultaneously? Thanks guys!
string pathTo = ...
foreach(char path in Random6CharString())
{
System.IO.Directory.CreateDirectory(pathTo); //Method to create folders on Desktop
}
You're using pathTo instead of the path variable of your foreach. So you're trying to create two folders with the same name in the same location (which it doesn't by the way, CreateDirectory can't overwrite an existing folder).
Look at your code:
string pathTo = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/" + "SYS_" + Random6CharString() + "/"; //Creates random directories
foreach(char path in Random6CharString())
{
System.IO.Directory.CreateDirectory(pathTo); //Method to create folders on Desktop
}
You're creating pathTo twice.
You could easily generate a random value for the path by using System.Guid.NewGuid(), by the way.
Related
Tried the below logic in windows form for file name incremental, if the file already exists in the specified path. but the files are created with the names "New1.txt2","New1.txt2.txt3". how the files can be created as "New1.txt", "New2.txt", "New3.txt"...."Newn.txt" on every button Click?
String filename =#"C:\path";
if (File.Exists(filename))
{
count++;
filename = filename + count.ToString()+".txt";
There is one more problem in your code. Why do you have file names like "New1.txt2","New1.txt2.txt3", "New1.txt2.txt3.txt4"? Because you don't keep initial filename somewhere. So, I'd propose to keep two variables for filenames: for instance, filename_initial and filename_current.
Try something like this:
String filename_initial = #"C:\path\New.txt";
String filename_current = filename_initial;
count = 0;
while (File.Exists(filename_current))
{
count++;
filename_current = Path.GetDirectoryName(filename_initial)
+ Path.DirectorySeparatorChar
+ Path.GetFileNameWithoutExtension(filename_initial)
+ count.ToString()
+ Path.GetExtension(filename_initial);
}
string UserFolder = Session["Username"].ToString();
if (!Directory.Exists("~/MisReports/EmailAttachment/"+UserFolder))
{
Directory.CreateDirectory("~/MisReports/EmailAttachment/"+UserFolder);
}
filePathE = Server.MapPath("~/MisReports/EmailAttachment/" + UserFolder + "/");
filePathE = filePathE + a + ".pdf";
bool isExist = File.Exists(filePathE);
if (isExist)
{
File.Delete(filePathE);
}
report.ExportToDisk(ExportFormatType.PortableDocFormat, filePathE);
I get the error
Could not find a part of the path
if (!Directory.Exists("~/MisReports/EmailAttachment/"+UserFolder))
{
Directory.CreateDirectory("~/MisReports/EmailAttachment/"+UserFolder);
}
in this area code does not enter if check although that the folder has not been created
The ~ is probably not evaluated if you are running on Windows. Windows is not Unix. Read up on Path.Combine, Environment.GetFolderPath and Environment.SpecialFolder on MSDN. You should build a path with code like
string directoryName = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "MisReports/EmailAttachment", UserFolder);
I am moving files from source folder to destination folder. Before moving files, I am checking that directory exists or not which is working fine. The issue is with my second check where I want to make sure that folder is not empty before moving files but it is not giving me correct result.
public void MoveFilesFromTempToSourceTbl()
{
//Moving all files from temp folder to orig folder.
string sourceFolder = (twitterDO.Path + "\\" + msgDate.Year.ToString() + "\\" + msgDate.Month.ToString() + "\\" + msgDate.Day.ToString() + "_Temp").Replace("\\", #"\");
string destinationFolder = (twitterDO.Path + "\\" + msgDate.Year.ToString() + "\\" + msgDate.Month.ToString() + "\\" + msgDate.Day.ToString()).Replace("\\", #"\");
string pattern = "*.txt";
if (Directory.Exists(sourceFolder))
{
if (File.Exists(pattern))
{
foreach (var file in new DirectoryInfo(sourceFolder).GetFiles(pattern))
{
file.MoveTo(Path.Combine(destinationFolder, file.Name));
}
}
if (Directory.GetFiles(sourceFolder).Length == 0) //Before deleting make sure that Temp folder is empty.
Directory.Delete(sourceFolder, true); // Delete Temp folder after moving all the contents.
}
}
I know I am making some small mistake but not sure what it is. Following is the screenshot of the result which I got in immediate window.
http://imgur.com/FZvo9cj
There's a bit of redundancy in your current code. Starting with the if-checks, here's how I would approach this:
var sourceDirectory = new DirectoryInfo(sourceFolder); // remember this, it is reused
if (sourceDirectory.Exists)
{
// Look for the files in the directory, if none found, will be empty array
foreach (var file in sourceDirectory.GetFiles(pattern))
{
file.MoveTo(Path.Combine(destinationFolder, file.Name));
}
// Re-check the directory for any remaining files
if (sourceDirectory.GetFiles(pattern).Length == 0) //Before deleting make sure that Temp folder is empty.
sourceDirectory.Delete(); // Delete Temp folder after moving all the contents.
}
As a small performance improvement, you could replace sourceDirectory.GetFiles() with sourceDirectory.EnumerateFiles() in the for-loop. This will allow you to start moving them as the method finds them, not after they have all been found.
You are passing "*.txt" into the File.Exists() call when you need to be passing a path.
You can read the Documentation here
Alternatively you could use something like this:
Directory.GetFiles(destinationFolder).Contains(filename)
I agree with David here but also I think the flow of you logic should be adjusted a bit. The File.Exixts(filename); should occur inside the foreach.
That will allow you to iterate each file and if it exists do something.
Try adding the following to check if any files exist in the location:
bool exist = Directory.EnumerateFiles(sourceFolder, "*.txt").Any();
I'm working on a project where we generating folders for users, my question is that is it possible to create those folders with one particular user as admin in code behind?
if (!Directory.Exists(Server.MapPath("~/Files/" + compamyFolder + "/User/" + folder)))
{
Directory.CreateDirectory(Server.MapPath("~/Files/" + compamyFolder + "/User/" + folder));
}
Use the below code as per http://forums.asp.net/p/1226236/2209871.aspx:
string subPath ="ImagesPath"; // your code goes here
bool isExists = System.IO.Directory.Exists(Server.MapPath(subPath));
if(!isExists)
System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
Happy coding!!
how about
string folderPath = #"C:\myRootFolder";
if(!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
Hello everyone and well met! I have tried a lot of different methods/programs to try and solve my problem. I'm a novice programmer and have taken a Visual Basic Class and Visual C# class.
I'm working with this in C#
I started off by making a very basic move file program and it worked fine for one file but as I mentioned I will be needing to move a ton of files based on name
What I am trying to do is move .pst (for example dave.pst) files from my exchange server based on username onto a backup server in the users folder (folder = dave) that has the same name as the .pst file
The ideal program would be:
Get files from the folder with the .pst extension
Move files to appropriate folder that has the same name in front of the .pst file extension
Update:
// String pstFileFolder = #"C:\test\";
// var searchPattern = "*.pst";
// var extension = ".pst";
//var serverFolder = #"C:\test3\";
// String filename = System.IO.Path.GetFileNameWithoutExtension(pstFileFolder);
// Searches the directory for *.pst
DirectoryInfo sourceDirectory = new DirectoryInfo(#"C:\test\");
String strTargetDirectory = (#"C:\test3\");
Console.WriteLine(sourceDirectory);
Console.ReadKey(true);>foreach (FileInfo file in sourceDirectory.GetFiles()) {
Console.WriteLine(file);
Console.ReadKey(true);
// Try to create the directory.
System.IO.Directory.CreateDirectory(strTargetDirectory);
file.MoveTo(strTargetDirectory + "\\" + file.Name);
}
This is just a simple copy procedure. I'm completely aware. The
Console.WriteLine(file);
Console.ReadKey(true);
Are for verification purpose right now to make sure I'm getting the proper files and I am. Now I just need to find the folder based on the name of the .pst file(the folder for the users are already created), make a folder(say 0304 for the year), then copy that .pst based on the name.
Thanks a ton for your help guys. #yuck, thanks for the code.
Have a look at the File and Directory classes in the System.IO namespace. You could use the Directory.GetFiles() method to get the names of the files you need to transfer.
Here's a console application to get you started. Note that there isn't any error checking and it makes some assumptions about how the files are named (e.g. that they end with .pst and don't contain that elsewhere in the name):
private static void Main() {
var pstFileFolder = #"C:\TEMP\PST_Files\";
var searchPattern = "*.pst";
var extension = ".pst";
var serverFolder = #"\\SERVER\PST_Backup\";
// Searches the directory for *.pst
foreach (var file in Directory.GetFiles(pstFileFolder, searchPattern)) {
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
// Gets the user name based on file name
// e.g. DaveSmith.pst would become DaveSmith
var userName = theFileInfo.Name.Replace(extension, "");
// Sets up the destination location
// e.g. \\SERVER\PST_Backup\DaveSmith\DaveSmith.pst
var destination = serverFolder + userName + #"\" + theFileInfo.Name;
File.Move(file, destination);
}
}
System.IO is your friend in this case ;)
First, Determine file name by:
String filename = System.IO.Path.GetFileNameWithoutExtension(SOME_PATH)
To make path to new folder, use Path.Combine:
String targetDir = Path.Combine(SOME_ROOT_DIR,filename);
Next, create folder with name based on given fileName
System.IO.Directory.CreateDirectory(targetDir);
Ah! You need to have name of file, but with extension this time. Path.GetFileName:
String fileNameWithExtension = System.IO.Path.GetFileName(SOME_PATH);
And you can move file (by File.Move) to it:
System.IO.File.Move(SOME_PATH,Path.Combine(targetDir,fileNameWithExtension)
Laster already show you how to get file list in folder.
I personally prefer DirectoryInfo because it is more object-oriented.
DirectoryInfo sourceDirectory = new DirectoryInfo("C:\MySourceDirectoryPath");
String strTargetDirectory = "C:\MyTargetDirectoryPath";
foreach (FileInfo file in sourceDirectory.GetFiles())
{
file.MoveTo(strTargetDirectory + "\\" + file.Name);
}