Creating Subdirectory function in C# - c#

I am currently attempting to create a function code that creates a subdirectory inside a user-specific path by having the user input the Directory path and then in main use the Directory.GetDirectories(arwgs) function to get a string array of there path.
This code works for the first attempt but after rerunning it again it creates a folder in same directory in the that I don't want to do again.
Good:
Directorys Created S:\Shop....\600\UnitCalFall
Bad:
Directorys Created S:\Shop\600\UnitCalFall\UnitCalFall
or
Directorys Created S:\Shop\600\UnitCalFall\UnitCalDone
I am trying to make the function as fast and integrative as possible so incase the user wants to create more than one or two folders.
The code is shown below:
static void UnitCalFolderCheck(string[] sDirectoryPath, string[] NewFolder)
{
//possible method can be constructed that checks for if a option UnitCallFolder has been created
for (int index = 0; index < sDirectoryPath.Length; index++)
{
//for each directory in the path if a folder named as UnitCalDONE in order to store CSV files data that has already been stored and conducted.
//ig a foldered labeled as such is already created then do not create this folder
string sCurrentPath = sDirectoryPath[index];
//check if current directory path already is created by the newfolder length path
//NEED TO CREATE A VARIABLE THAT CHECKS IF ANY OF THE SUBSTRINGS ARE TRUE AND IF SO DO NOT CHECK FOR NEW DIRECTORY
bool bexist = false;
//Console.WriteLine(sCurrentPath);
//also check if a the current path also has the UnitCalFolder Done already. This is because the newDirpath
//Will be a duplication of each folder and this can cause problems for the for loop
//append for each dirpath the folder information
for (int i = 0; i < NewFolder.Length; i++)
{
int NewFolderLength = NewFolder[i].Length;
string sNewDirPath = sCurrentPath + NewFolder[i];
string substring = sCurrentPath.Substring(sCurrentPath.Length - NewFolderLength);
//looping around the new possible created folders based on the substring paths
foreach (string x in NewFolder)
{
//THIS DOESNT CHECK IF FOLDER IS DIFFERENT FROM THE OTHER CONTAINER
// Console.WriteLine(x);
if (!substring.Contains(x)) //not working propery
{
bexist = true;
}
else
{
bexist = false;
}
}
if (!Directory.Exists(sNewDirPath) && (bexist == true) )
{
Directory.CreateDirectory(sNewDirPath);
Console.WriteLine("Directorys Created" + sNewDirPath);
}
}
}
}

*A crude way of fixing but when looking back this can work for folders with the suffix "UnitCal". At least for my directory. Not the most elegant but works.
static void UnitCalFolderCheck(string[] sDirectoryPath, string[] NewFolder)
{
//possible method can be constructed that checks for if a option UnitCallFolder has been created
for (int index = 0; index < sDirectoryPath.Length; index++)
{
//for each directory in the path if a folder named as UnitCalDONE in order to store CSV files data that has already been stored and conducted.
//ig a foldered labeled as such is already created then do not create this folder
string sCurrentPath = sDirectoryPath[index];
//Console.WriteLine(sCurrentPath);
//int[] iexist = new int[NewFolder.Count()]; //if substring exist already then dont create new directory
//int inotexist = 0;
string sNewDirPath;
string FolderIndexPath = "";
//for every new folder in the path check if the directory with substring already exist
for(int x = 0; x < NewFolder.Length; x++)
{
int NewFolderLength = NewFolder.Length; //length of the new folder to append to newdirpath string
//string substring = sCurrentPath.Substring(sCurrentPath.Length - NewFolderLength);
//UnitCalDone folder first iteration
//UNitCalFall folder secnond iteration
Console.WriteLine("========================================================================");
Console.WriteLine(sCurrentPath);
Console.WriteLine(NewFolder[x]);
if (!sCurrentPath.Contains("UnitCal"))
{
// iexist[x] = 0;
sNewDirPath = sCurrentPath + NewFolder[x];
// Determine whether the directory exists.
if (!Directory.Exists(sNewDirPath))
{
//check if new path already exist if so then do nothing
Console.WriteLine("NEWPATH->>>");
//Directory.CreateDirectory(sNewDirPath);
Console.WriteLine(sNewDirPath); //check that none of this values contain the selected values
}
}
else
{
//do nothing
}
}
}//end of for loop method
}//end of unitCalFolderCheckr code here*

Related

How to (StartsWith) start with 4th letter?

I have a question. I want to copy specific files in 'New folder' to 'Target' folder by clicking a button. In 'New folder' contains various of file with different name. For example: "abcUCU0001", "abbUCA0003", "hhhUCU0012", "aaaUCS0012" and many more. 'New folder' contains more than 1000 files and have same 10 letters in its name. I want to copy 10 files and its name must have "UCU". I don't know how to copy using (startsWith) starting with 4th letter.
Sorry for my bad grammar.
private void button1_Click(object sender, EventArgs e)
{
string FROM_DIR = #"C:\Users\Desktop\Source";
string TO_DIR = #"C:\Users\Desktop\Target";
DirectoryInfo diCopyForm = new DirectoryInfo(FROM_DIR);
DirectoryInfo[] fiDiskfiles = diCopyForm.GetDirectories();
string filename = "UCU";
int count = 0;
foreach (DirectoryInfo newfile in fiDiskfiles)
{
try
{
if (newfile.Name=="New folder")
{
foreach (FileInfo file in newfile.GetFiles())
{
if(file.FullName.StartsWith(filename))
{
File.Copy(file.FullName, Path.Combine(TO_DIR,file.Name));
count++;
if (count == 10)
{
break;
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
MessageBox.Show("success");
}
I expect after click a button, 10 files with name "UCU" will copied to Target folder.
If all the files are in the same directory (no sub-directories), then you can get all files using:
//assuming diCopyForm is the new folder reference
// ? denotes 1 character while * is multiple chars
var files = diCopyForm.GetFiles("???UCU*");
And then just copy them across. For more complex criteria, I would get all the files and use LINQ to filter through.
Details about the search pattern used
If there are a lot of files in the folder then it might be more efficient to use the EnumerateFiles method
The EnumerateFiles and GetFiles methods differ as follows: When you
use EnumerateFiles, you can start enumerating the collection of names
before the whole collection is returned; when you use GetFiles, you
must wait for the whole array of names to be returned before you can
access the array. Therefore, when you are working with many files and
directories, EnumerateFiles can be more efficient.
You can check if file name has "UCU" in 4th position with string.IndexOf:
//string filename = "UCU";
if (file.FullName.IndexOf(filename) == 3)

Cannot implicitly convert type 'Microsoft.Office.Interop.Outlook.MAPIFolder' to 'Microsoft.Office.Interop.Outlook.Folder'

I am new to C#. I am able to code in C# because I am a java programmer, and C# is also Object Oriented. Please bear with me as some of the names of the terminologies that I use here to explain might be of java.
How do I iterate among the subfolders using the folder method in C#? I have initialized the subFolders object of the method folders of the class Outlook to store all the subfolders if there are any. And I am using a for loop to iterate among them. In the loop, I am trying to initialize a subFolder object of the folder method to hold the current iterating folder from the subFolders object.
I am getting a conversion error while trying to assign the current iterating folder, to the subFolder object.
Error Message: Cannot implicitly convert type 'Microsoft.Office.Interop.Outlook.MAPIFolder' to 'Microsoft.Office.Interop.Outlook.Folder'. An Implicit conversion exists (are you missing a cast?)
Below is a part of the code:
static void enumerateFolders(Outlook.Folder folder) //Checks if there are sub folders inside the Inbox folder.
{
Outlook.Folders subfolders = folder.Folders;
if (subfolders.Count > 0)
{
for (int i = 0; i < subfolders.Count; i++)
{
Outlook.Folder subFolder = subfolders[i]; //This is where I am getting the error.
iterateMessages(subFolder);
}
}
else
{
iterateMessages(folder);
}
}
I used mapifolders, and this code has worked for many versions of outlook ( used this to build up the \\pst\folder\folder2 type paths we are used to)
public struct Flder
{
public String name;
public MAPIFolder folder;
}
...
private static void WalkTree(Folders topfolder, String path)
{
if (topfolder.Count > 0)
{
foreach (MAPIFolder f in topfolder.AsParallel())
{
if (!f.Name.Contains("Public"))
{
Flder fld = new Flder();
fld.name = path + "\\" + f.Name;
fld.folder = f;
folderList.Add(fld);
try
{
WalkTree(f.Folders, path + "\\" + f.Name);
}
catch
{
continue; // skip any errors
}
}
}
}
}
I got the solution. All I had to do is typeCast subfolders[i] to Outlook.Folder type. Below is the code:
static void enumerateFolders(Outlook.Folder folder) //Checks if there are sub folders inside the Inbox folder.
{
Outlook.Folders subfolders = folder.Folders;
if (subfolders.Count > 0)
{
for (int i = 0; i < subfolders.Count; i++)
{
Outlook.Folder subFolder = (Outlook.Folder) subfolders[i]; //Solution: type casted
iterateMessages(subFolder);
}
}
else
{
iterateMessages(folder); //This implements the core functionality of the program. It iterates amongst the emails to retrieve the clearstream attachment.
}
}

SSIS Script Task Check if a folder is empty

Within a SSIS Script Task, I have the below code that checks if a folder is empty. I then want to pass if it is or not into the variable 'Dim_File_Count' and use a Precedence constraint to move onto the next task if successful. However my code keeps stating the folder is empty, even when it's not:
public void Main()
{
//string FolderName = Dts.Variables["User::Tech_Dim"].Value.ToString();
if (File.Exists(Dts.Variables["User::Tech_Dim"].Value.ToString())==false)
{
Dts.Variables["User::Dim_File_Count"].Value = 0;
MessageBox.Show("folder empty");
}
else
{
Dts.Variables["User::Dim_File_Count"].Value = 1;
MessageBox.Show("folder is not empty");
}
Dts.TaskResult = (int)ScriptResults.Success;
}
You can use the Length property of the GetFiles method of the Directory class to check if there are any files in the specified folder. The optional third SearchOption parameter of GetFiles can be used if searching sub-directories is necessary, i.e. SearchOption.AllDirectories, with the default checking only the parent folder.
if (Directory.GetFiles(Dts.Variables["User::Tech_Dim"].Value.ToString(), "*").Length > 0)
{
Dts.Variables["User::Dim_File_Count"].Value = 0;
MessageBox.Show("folder empty");
}
else
{
Dts.Variables["User::Dim_File_Count"].Value = 1;
MessageBox.Show("folder is not empty");
}

Formatting a Linux path in C#

So I am making a file browser using the WinSCP library in C#. The files and folders from the remote server are loaded into a ListView, and I have an event on the ListView_DoubleClick event that will go and get the files for that folder. However my problem is, the "CurrentPath" returned from WinSCP is built like so;
"/eddata/T". Now if a user goes back up a directory, the path returned is "/eddata/T/../". If the user then goes into another folder called "Bob", the path now looks like; "/eddata/T/../Bob".
I want a way so I can display the current path in a user friendly way. So when a user is in the directory; "/eddata/T/" and they go up a level, a label should tell them they are in; "/eddata/";
This is my attempt but isn't working as expected, it doesn't deal the event where a user goes back up two directories at the same time;
private string FormatPathString(string input)
{
String working = input;
bool replacement = true;
while (replacement)
{
string[] splits = working.Split('/');
splits = splits.AsEnumerable().Where(x => x != String.Empty).ToArray();
int? found_index = null;
for (int i = splits.Count() - 1; i > 0; i--)
{
if (splits[i] == "..")
{
found_index = i;
break;
}
}
if (found_index.HasValue)
{
replacement = true;
splits = splits.Where((val, idx) => (idx != found_index) && (idx != found_index - 1)).ToArray();
working = String.Join("/", splits);
}
else
{
replacement = false;
}
}
return working;
}
You can use the Path class.
string pathWithDots= "/eddata/T/../Bob";
string pathWithoutDots = Path.GetFullPath(pathWithDots); // Result: c:\eddata\Bob
however the Path class assumes that you are using a windows path and adds C: and changes slashes to backslashes so you will need to remove the C: at the start and replace all back slashes with forward slashes.
string pathNx = pathWithoutDots.Substring(2).Replace("\\", "/"); // Result: /eddata/Bob

Use a switch statement to create file directories?

I'm creating an app that's going to be installed on a number of devices and I'd like to automate the setup of the file system on each device's local disk as much as possible. Rather than use dozens of if statements is there a more streamlined way to do this using a switch statement?
if (System.IO.Directory.Exists(arctopithecusGalleryPath) == false)
{
System.IO.Directory.CreateDirectory(arctopithecusGalleryPath);
}
How about creating a method for that:
public void CreateIfNotExists(string path)
{
if (System.IO.Directory.Exists(path) == false)
{
System.IO.Directory.CreateDirectory(path);
}
}
And then use it in your code like this:
CreateIfNotExists(arctopithecusGalleryPath);
Or if you have multiple directories you can add them to list and call this method inside foreach statement:
List<string> folders = new List<string>();
folders.Add("a folder to create");
// add more folders
foreach(var folder in folders)
{
CreateIfNotExists(folder);
}
Store variables in array & loop them to avoid multiple IFs.
string[] arr1 = new string[] { arctopithecusGalleryPath, arctopithecusGalleryPath1, arctopithecusGalleryPath3 };
for (int i = 0; i < arr1.Length; i++)
{
if (System.IO.Directory.Exists(array[i]) == false){
System.IO.Directory.CreateDirectory(array[i]);
}

Categories