So I ran across this article for listing out virtual directories. And the article shows how I can specify a username and password for DirectoryEntry. But I'm still getting Access is denied.
There is still something I'm not grasping about permissions. Any ideas?
class Program
{
static void Main(string[] args)
{
//http://www.developmentnow.com/blog/2004/12/29/recursively-list-virtual-directories-in-iis-with-c-and-directoryservices/
// call the function once to kick it off
WriteVDirs("localhost", 2, "");
}
// function that recursively walks through IIS dir & vdirs & lists all the virtual directories
public static void WriteVDirs(string serverName, int SiteNumber, string path)
{
DirectoryEntry de =
new DirectoryEntry("IIS://" + serverName + "/W3SVC/" +
SiteNumber.ToString() + "/Root" + path);
de.Username = "my-machine/administrator";
de.Password = "admin";
DirectoryEntries dirs;
try
{
dirs = de.Children;
foreach (DirectoryEntry d in dirs)
{
if (0 == String.Compare(d.SchemaClassName, "IIsWebDirectory"))
{
string fullPath = path + "/" + d.Name;
WriteVDirs(serverName, SiteNumber, fullPath);
}
else if (0 == String.Compare(d.SchemaClassName, "IIsWebVirtualDir"))
{
string fullPath = path + "/" + d.Name;
Console.WriteLine(fullPath + " : " + d.Properties["Path"].Value);
WriteVDirs(serverName, SiteNumber, fullPath);
}
}
}
catch (Exception ex)
{
Console.WriteLine("ERROR: " + ex.Message);
}
}
}
Related
I have created a code to create folders with two Textboxes.
Textbox1 - customer number (XXXX).
Textbox2 - customer name.
I would like to be able to check if the customer number exists before creating the folder.
The newly created folder will be the combination of the two Textboxes (this is already solved).
I just need to be able to determine if the folder exists only with the customer number, as it is probably created with (customer number + customer name).
Current working code:
{
string no = textBox1.Text;
string client = textBox2.Text;
string carpeta = #"C:\" + no + " " + client;
string sourcePath = #"C:\main";
string destinationPath = #"C:\" + no + " " + client;
textBox1.Clear();
textBox2.Clear();
try
{
if (Directory.Exists(carpeta))
{
DialogResult y;
y = MessageBox.Show("Folder already exists\nDo you want to open it?", "AE.", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (y == DialogResult.Yes)
{
System.Diagnostics.Process.Start(#"C:\" + no + " " + client);
}
else
{
Close();
}
}
else
{
DialogResult x;
x = MessageBox.Show("The folder doesn't exist\nWant to create a folder?." + "\n" + no + " " + client, "AE.", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (x == DialogResult.Yes)
{
Directory.CreateDirectory(carpeta);
FileSystem.CopyDirectory(sourcePath, destinationPath, UIOption.AllDialogs);
System.Diagnostics.Process.Start(#"C:\" + no + " " + client);
}
else
{
Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.Message);
}
}
You could also each time you need the folder just do that:
public static void Main()
{
var username = "someuser";
var usernumber = "ABC123";
var mainDirectory = #"C:\Path\To\The\Main\Dir";
var pathToTheUserDirectory = Path.Combine(mainDirectory, $"{username}-{usernumber}");
// This line will create the directory if not exist or take the existing directory.
var directoryInfo = Directory.CreateDirectory(pathToTheUserDirectory);
var directoryPath = directoryInfo.FullName;
// ...
// or
// directoryInfo.Delete(recursive: true);
}
string[] dirs = Directory.GetDirectories(#"c:\", txtTextBox.Text + "*");
this will only get directrories starting with the desired Text
Edit: This is only a good solution if the customer number has fixed places (in you exaple 4 from 0000-9999)
Microsoft Documentation - check example below
I have the bit of code that searches the entire computer for a file and once found, should return that file. The problem is in the second function, the recursive one. Once the file is found, it should return, which it does, but for some reason, even after returning the value, it continues the recursive search.
I don't get it. I'd still consider myself new to programming so please explain in detail if you see what I'm doing wrong.
public string SearchDirectory(string dir, string fileName)
{
string foundDir = "";
bool fileFound = false;
// Gets all files from directory and creates list of matches to fileName
try
{
foreach (string match in Directory.GetFiles(dir, fileName))
{
// Returns the first found match as a path and breaks loop
Console.WriteLine("Checked path: " + dir + ".");
if (File.Exists(dir + #"\" + fileName))
{
Console.WriteLine("FOUND!!");
fileFound = true;
foundDir = dir;
break;
}
if (fileFound == true)
{
break;
}
}
}
catch
{
Console.WriteLine("Access to path: " + dir + " denied.");
}
// If fileName isn't found in directory, it searches each new directory
// The last directory it will check is the last one in the original directory
if (fileFound == false)
{
try
{
foreach (string newDirectory in Directory.GetDirectories(dir))
{
Console.WriteLine("Checked path: " + dir + ".");
SearchDirectory(newDirectory, fileName);
}
}
catch
{
Console.WriteLine("Access to path: " + dir + " denied.");
}
// fileName does not exist in starting directory
}
else
{
return foundDir;
}
return "";
}
Your recursive call is ignoring the returned value. You should instead check to see if it found something so you can stop searching more sub-directories.
foreach (string newDirectory in Directory.GetDirectories(dir))
{
Console.WriteLine("Checked path: " + dir + ".");
var result = SearchDirectory(newDirectory, fileName);
if(result != "") return result;
}
You could just do this instead:
public string SearchDirectory(string dir, string fileName)
{
return Directory
.EnumerateFiles(dir, fileName, SearchOption.AllDirectories)
.FirstOrDefault() ?? "";
}
I have used the following below code to convert the zip file to enc file but its not working perfectly, please help me to solve this issue
Also if there is any third party tool to convert the zip to enc file please mention the details about it .
Thanks in Advance
try
{
string startPath = "";
string path = #"F:\Augustin\UpTest\Upload\";
DirectoryInfo objdirinfovikramfile = new DirectoryInfo(path);
if (objdirinfovikramfile.Exists)
{
errorcheck = "a";
foreach (DirectoryInfo objdirenmvikramfile in objdirinfovikramfile.GetDirectories())
{
string checkvikramfile = "";
checkvikramfile = objdirenmvikramfile.Name;
startPath = path + checkvikramfile + "\\";
string zipPath = path + checkvikramfile + ".zip";
string sub = zipPath.Split('\\').Last();
Boolean decrypt = false;
FileManager obj = new FileManager();
Int64 secure_count = 0;
while (secure_count <= 3 && !decrypt)
{
decrypt = obj_viki1.Decryption(zipPath, zipPath.Replace(".zip", ".enc"), "dietcoke1"); //DLL Function
secure_count++;
}
if (secure_count > 3 && !decrypt)
{
File.Copy(zipPath, path + "\\FAILED\\" + zipPath.Split('\\').Last(),true );
File.Copy(zipPath, path + "\\FAILED\\" + zipPath.Split('\\').Last(), true);
}
else
{
File.Copy(zipPath, path + "\\SUCCESS\\" + zipPath.Split('\\').Last(), true);
}
}
}
}
catch (Exception ex)
{
Error_log("FileProcess Enc: " + errorcheck + " ", ex.ToString());
Application.Exit();
}
THIS QUESTION IS ANSWERED!
I need to get all files from dropbox. But I cant finish my recursive function, it doesnt work, i have an idea why it doesnt work, but i dont know how to fix it
private void getAllFiles(string path)
{
var dropCon = DatabaseDropbox.Instance();
if (dropCon.IsConnect())
{
ICloudDirectoryEntry folder = dropCon.DropboxStorage.GetFolder(path);
foreach (ICloudFileSystemEntry fsentry in folder)
{
if (fsentry is ICloudDirectoryEntry) // IF FOLDER
{
}
else // IF FILE
{
Console.WriteLine(path + " " + fsentry.Name);
ListViewItem lvi = new ListViewItem(fsentry.Name);
lvi.SubItems.Add(path);
listViewFolders.Items.Add(lvi);
}
}
foreach (ICloudFileSystemEntry fsentry in folder)
{
if (fsentry is ICloudDirectoryEntry) // IF FOLDER
{
var mpath = path + "/" + fsentry.Name;
getAllFiles(mpath);
}
else // IF FILE
{
Console.WriteLine(path + " " + fsentry.Name);
ListViewItem lvi = new ListViewItem(fsentry.Name);
lvi.SubItems.Add(path);
listViewFolders.Items.Add(lvi);
}
}
}
}
If its finds file, it adds it to the list (C# form).
HOW IT DOESNT WORK:
It will list all files in the first directory,
then it will go to the first folder found, lets call that folder "fol1".
After it scans all "fol1", it adds found files to the list, which is good.
But then , when it should go back and search for more files in other directories , "fol2","fol3". Recursion just exists itself and it doesnt do that. So thats my problem.
FOUND RESULTS:
https://gyazo.com/fda8fde13dfbf32f35d39b87712b5751
ACTUAL FOLDERS:
https://gyazo.com/619e5c46bbc113d7d23a56b225f4f209
https://gyazo.com/265034521f317bf0d308910929d1664c
https://gyazo.com/ed9fe5375e1b21f54bbd1f127085c255
Thanks.
WORKING CODE :
private void getAllFiles(string path)
{
var dropCon = DatabaseDropbox.Instance();
if (dropCon.IsConnect())
{
ICloudDirectoryEntry folder = dropCon.DropboxStorage.GetFolder(path);
foreach (ICloudFileSystemEntry fsentry in folder)
{
if (fsentry is ICloudDirectoryEntry) // IF FOLDER
{
var mpath = path + "/" + fsentry.Name;
getAllFiles(mpath);
}
else // IF FILE
{
Console.WriteLine(path + " " + fsentry.Name);
ListViewItem lvi = new ListViewItem(fsentry.Name);
lvi.SubItems.Add(path);
listViewFolders.Items.Add(lvi);
}
}
}
}
private void getAllFiles(string path)
{
var dropCon = DatabaseDropbox.Instance();
if (dropCon.IsConnect())
{
ICloudDirectoryEntry folder = dropCon.DropboxStorage.GetFolder(path);
foreach (ICloudFileSystemEntry fsentry in folder)
{
if (fsentry is ICloudDirectoryEntry) // IF FOLDER
{
var mpath = path + "/" + fsentry.Name;
getAllFiles(mpath);
}
else // IF FILE
{
Console.WriteLine(path + " " + fsentry.Name);
ListViewItem lvi = new ListViewItem(fsentry.Name);
lvi.SubItems.Add(path);
listViewFolders.Items.Add(lvi);
}
}
}
}
I wrote an app for going through very large fileshares and while it copies them to the new location, another HD in this case, it breaks what's being copied over into folders containing 4,500 or less items(Libraries to be synced to sharepoint online). Compensating for long file paths. Here is a code sample of the functions I have working in tandem that takes in the source and destination then does the copying breaking described above:
Edit:
Alright I found a solution and this method below is working as I want it to, it is really slow as you can imagine looking at how I have it counting the childitems as it's running though so if anyone has a better/faster solution to the problem please feel free to post it. Otherwise, thank you all very much for the help, it's much appreciated. Here's the code I currently have:
#region Recursive_Copy
public static List<string> OutOfReachAreas = new List<string>();
private static List<FileInfo> Overflow = new List<FileInfo>();
private static List<string> AccessDeniedList = new List<string>();
private static bool FirstTime = true;
private static int LibraryCount { get; set; }
private static bool ToSwith = false;
private static int CountLimit = 4250;
public static void RecursiveCopy(string SourceDir, string DestDir)
{
if (!FirstTime)
{
LibraryCount =
((Directory.GetDirectories((Program.DestinationContainer + "\\" + "Library" + Program.LibraryCounter.ToString()), "*", SearchOption.AllDirectories).Count())
+ (Directory.GetFiles((Program.DestinationContainer + "\\" + "Library" + Program.LibraryCounter.ToString()), "*", SearchOption.AllDirectories).Count()));
}
if (LibraryCount <= CountLimit && !FirstTime)
{
try
{
DirectoryInfo dir = new DirectoryInfo(SourceDir);
DirectoryInfo[] dirs = dir.GetDirectories();
FileInfo[] files = dir.GetFiles();
string CurrentLibrary = "Library" + Program.LibraryCounter.ToString();
if (!Directory.Exists(DestDir))
{
Directory.CreateDirectory(DestDir);
}
if (Overflow.Count() != 0)
{
foreach (var OverflowInst in Overflow)
{
string NewestLibrary = Program.DestinationContainer + "\\" + "Library" + Program.LibraryCounter + "\\" + OverflowInst.Name;
if (!File.Exists(NewestLibrary))
{
OverflowInst.CopyTo(NewestLibrary, false);
}
}
Overflow.Clear();
}
foreach (var file in files)
{
try
{
DirectoryInfo TestPath = new DirectoryInfo(Program.DestinationContainer + "\\" + CurrentLibrary);
int TestPathCount = (TestPath.GetDirectories("*", SearchOption.AllDirectories).Count()) + (TestPath.GetFiles("*", SearchOption.AllDirectories).Count());
if (TestPathCount <= CountLimit)
{
string temppath = Path.Combine(DestDir, file.Name);
DirectoryInfo TestTemp = new DirectoryInfo(temppath);
if (!TestTemp.Exists && !AccessDeniedList.Contains(file.Name))
{
file.CopyTo(temppath, true);
}
}
else
{
FileInfo OverflowToAdd = new FileInfo(file.FullName);
Overflow.Add(OverflowToAdd);
}
}
catch (UnauthorizedAccessException)
{
AccessDeniedList.Add(file.Name);
}
}
foreach (var subDir in dirs)
{
DirectoryInfo TestPath = new DirectoryInfo(Program.DestinationContainer + "\\" + CurrentLibrary);
int TestPathCount = (TestPath.GetDirectories("*", SearchOption.AllDirectories).Count()) + (TestPath.GetFiles("*", SearchOption.AllDirectories).Count());
if (TestPathCount <= CountLimit)
{
if (ToSwith)
{
ToSwith = false;
string PathToSwitch = Program.DestinationContainer + "\\" + "Library" + Program.LibraryCounter.ToString();
RecursiveCopy(SourceDir, PathToSwitch);
}
string temppath = Path.Combine(DestDir, subDir.Name);
RecursiveCopy(subDir.FullName, temppath);
}
else
{
DirectoryInfo CurrentDir = new DirectoryInfo(DestDir);
RecursiveCopy(SourceDir, (Program.DestinationContainer + "\\" + "Library" + Program.LibraryCounter.ToString()));
}
}
}
catch (PathTooLongException)
{
DirectoryInfo DirInst = new DirectoryInfo(SourceDir);
OutOfReachAreas.Add(DirInst.FullName);
}
catch (Exception e)
{
Console.WriteLine("\nError During Copying:\n" + e.Message);
}
}
else
{
++Program.LibraryCounter;
FirstTime = false;
ToSwith = true;
string LibraryToMake = Program.DestinationContainer + "\\" + "Library" + (Program.LibraryCounter.ToString());
Console.WriteLine("Building Library" + (Program.LibraryCounter.ToString()) + "...");
Directory.CreateDirectory(LibraryToMake);
RecursiveCopy(SourceDir, LibraryToMake);
}
}
#endregion
Like chais said in comments, you need the subdirectory search to be recursive.
The MS example calls itself for EACH subdirectory, so it walks the entire directory tree. You could do something similar by replacing:
foreach (var dir in FolderList1)
{
Destination = Destination + "\\" + dir.Name;
CopyItems(dir, Destination);
}
with
foreach (var dir in FolderList1)
{
Destination = Destination + "\\" + dir.Name;
CopyItems(dir, Destination);
foreach (Directory subDir in dir.GetDirectories())
{
BreakMain(subDir, Destination);
}
}
You've got some other things that will have to be fixed to move to this recursive design, but that's the jist of the MS example.