I need to verify that a unix folder exists, from my C# application using SharpSsh.
I thought of trying this:
SshExec.RunCommand("-d " + folder)
But the result is always '2' regardless if the folder is there or not. I could implement something using:
Sftp.GetFileList(folder)
But prefer not to because this folder may contain numerous files and It causes a delay while all of them are retrieved which is not elegant.
Any ideas?
Edit:
I tried this:
string folder = "/foldername";
string result = sshExec.RunCommand("[ -d " + folder + "] && echo 'true' || echo 'false'");
if (result == "false")
throw new Exception("Directory " + foldername+ " + is not found.");
String 'result' is set as "false\n" even though the directory exists. If I skip the check I can work with the directory without problems.
Use
SshExec.RunCommand("ls -la " + folder)
or
SshExec.RunCommand("ls " + folder)
if your folder is not hidden and you dont need size information
Cheap command that will fill your output string with permissions and folder info if exists
Related
In my program I have to check, if a directory exists or not and when it doesn't the directory shall be created. I need that in two different classes. It works fine in the one, not at all in the other class. I could probably make this function a method and just call it in both places, but I was wondering how that can be.
So here's my code in class one:
string path = #"F:\yyyy\images\" + input+ "\\" + now + "\\";
if (!File.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
Where "now" is a string, containing the current date and input is just another string.
Code in class two:
string path = #"F:\yyyy\images\" + command[2] + "\\" + now+ "\\";
if (!File.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
The second example always runs, no matter if the directory exists or not.
command[2] is a string, basically being the same as "input" in the first example. To test if its really the same, I did this in class 2:
System.IO.Directory.CreateDirectory(path + 1);
And it made a "1" directory, inside the directory, that class 1 just created.
If you're trying to find check if a directory exists, use Directory.Exists instead of File.Exists. Your if check is unnecessary though. The Directory.Create method already does this check.
From the docs:
if (!File.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
You're checking to see if a file exists, and if it doesn't creating a directory with the name. At the end of this activity, there is still no directory that exists. What you want to do is see if the directory exists:
string path = #"F:\yyyy\images\" + input + "\\" + now;
if (!Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
Also: Notice that I got rid of the trailing backslash. It's not strictly necessary, and I tend to find it adds noise.
you want to check if the directory exists or the file?
Directory.Exists
File.Exists
Here's a GIF showing whats wrong
NOTE: It works perfectly fine with DownloadFile() it downloads under the right name and path (Even the mbox before it is correct) - But everything else after it fails to be the right name and path.
Need the .exe to test?
https://github.com/ImReallyShiny/SAIO/blob/master/Test.exe
(Scan it if needed, But it is 100% safe)
This is absolute wizardry that's going on.
Somehow when I run my "Auto-Update" code from the "Start" Button on Visual Studio, It outputs the correct file path and file name (with .exe)...
But when I open the Built .exe, It does some wizardry resulting in it slashing everything after (& Including) the "-" but keeping the .exe somehow.
The code is EXACTLY the same on BOTH .exe's the only thing I could see as the reason, Is some issue with Webclient Getting the version more than 1 time (Yet its tied to a string var so it shouldn't matter) or some kind of Glitch with my VisualStudio setup (Cache, Propogation, PC Restart Needed or something)
This is a hard question to explain, So I added some Inline Commenting to explain where the issue is and what it is.
Code:
//Using WebClient, get the Newest File Version;
using (System.Net.WebClient wc = new System.Net.WebClient())
{
//Latest Version; (This is the number after the - for the filename - Excluding .exe)
string LatestVersion = wc.DownloadString("https://raw.githubusercontent.com/ImReallyShiny/SAIO/master/version.txt");
//This is the Location itself e.g C:/Users/Shiny/Desktop/{appname}.exe
string ExecutableLocation = typeof(Program).Assembly.CodeBase.Replace("file:///", "");
//The build's File Version;
string CurrentVersion = FileVersionInfo.GetVersionInfo(ExecutableLocation).ProductVersion;
//Final Name String; As you can see it SHOULD output as: AppName-1.2.4.5.exe
string CurrentExecutableName = typeof(Program).Assembly.GetName().Name + "-" + LatestVersion + ".exe";
//If the Latest Version is Newer then the Current Version;
if (LatestVersion != CurrentVersion)
{
//Download the Latest Version of the EXE file; (Gets the name and path perfectly fine)
wc.DownloadFile("https://github.com/ImReallyShiny/SAIO/raw/master/SAIO.exe", CurrentExecutableName);
//Show a MessageBox asking to open Explorer to the file; - This should output "{Path}/AppName-1.2.4.5.exe" but it only does when opening from VS
DialogResult mb = MessageBox.Show("Continue usage on the new update. Open Explorer and go to the Directory containing the updated .exe located at: " + ExecutableLocation.Replace("SAIO.EXE", CurrentExecutableName + " ?\""), "New Update Downloaded!", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
if (mb == DialogResult.Yes)
{
//Go to where SAIO is and select the New Update.exe; (This also fails to select the right .exe, It selects "SAIO.EXE" when it should be selecing the AppName-1.2.4.5.exe
Process.Start("explorer.exe", "/select,\"" + ExecutableLocation.Replace("/", "\\").Replace("SAIO.EXE", CurrentExecutableName) + "\"");
}
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
Get what im saying?
This is simply that the filename is (sometimes) SAIO.exe or some other case.
Seeing as Replace doesn't have an overload to allow you to specify InvariantCultureIgnoreCase (or somethingElseIgnoreCase), the best solution is to use Path.GetDirectoryName to get the full folder name you want, rather than just expecting there to be exactly one SAIO.EXE in the path.
E.g. your last line could be (untested):
Process.Start("explorer.exe", "/select,\"" +
Path.GetDirectoryName(ExecutableLocation.Replace("/", "\\"))
+ "\\" + CurrentExecutableName + "\"");
GetDirectoryName handles / separators fine, but you'll still want to adjust them sometime to ensure the explorer call to works properly.
Really that last line should be (again untested):
Process.Start("explorer.exe", "/select,\"" +
Path.Combine(Path.GetDirectoryName(ExecutableLocation.Replace("/", "\\")),
CurrentExecutableName) + "\"");
I have a C# application (WCF soap service) that is creating PDF documents and save in in the path that is defined in web.config. Consider for example path is: C:\Doc\Pdf\ that in the code path is in location variable. I like to generate folders for each day and stores the pdfs for that day on its folder.
I tried to use CreateDirectory but I don't know how specify name of the folder to generate.
This code only save the PDF in the C:\Doc\Pdf\ and it is not creating any directory:
string pdfFileName = "Application" + "_" + documentData.APPLICATIONDATE.ToString("MMddyyyy") + "_" + documentData.APPLICATIONDATE.ToString("hhmmsstt") + "_" + documentData.BorrowerLastName;
location = ConfigurationManager.AppSettings["PdfPath"].ToString();
DirectoryInfo di =System.IO.Directory.CreateDirectory(location);
wordDoc.SaveAs(location + pdfFileName, WdSaveFormat.wdFormatPDF);
In this context I think that you could simply use the Directory.CreateDirectory method passing the combined path that you expect to be created.
The Directory method called CreateDirectory works creating all the directories missing in the path specified and if the path already exists doesn't throw exceptions, it simply does nothing
So your code coulde be
string dayPath = DateTime.Today.ToString("yyyyMMdd");
string newPath = Path.Combine(location, dayPath);
Directory.CreateDirectory(newPath);
........
In C#, for changing attribute of folder, I use FileAttributes.
Example:
myfolder= "C:\\Test Programs\\Avatar";
DirectoryInfo ss = new DirectoryInfo(myfolder);
ss.Attributes = FileAttributes.Normal;
--> Done! Attribute of Avatar is Normal.
But, with some folder which name are " ":
myfolder= "C:\\Test Programs\\ ";
My program doesn't throw any errors but attribute of that folder isn't change.
What can i do?
Link to fullsize image
(some viruses created a hidden folder with name is " " and moved all data on usb flash disk into it. I want to remove hidden attribute of that folder)
My English grammar isn't good. Sorry about that!
Done!. I added "\\" into myfolder.
With folder Avatar --> myfolder= "C:\\Test Programs\\Avatar\\";
With folder which name is " " --> myfolder= "C:\\Test Programs\\ \\";
And my program set Attribute of that folder to Normal.
Thanks every one!.
Try adding + System.Net.WebUtility.HtmlDecode(#" ") +"\\" to the end of your directory name instead of the space.
Your string will look like this:
myfolder= "C:\\Test Programs\\ " + System.Net.WebUtility.HtmlDecode(#" ") + "\\";
I'm making an Outlook plugin which will automatically save messages to a file server when received. This part of the code simply doesn't do what it's asked to do!
//RelevantDirectory[0] is the root folder where I want to save stuff, and sits on a mapped network drive where I have full admin permissions.
System.IO.Directory.CreateDirectory(RelevantDirectory[0] + "\\Email Correspondence\\");
System.IO.Directory.CreateDirectory(RelevantDirectory[0] + "\\Email Correspondence\\Outgoing");
mail.SaveAs(RelevantDirectory[0] + "\\Email Correspondence\\Outgoing\\" + mail.SenderName + " - " + string.Format("text-{0:yyyy-MM-dd_hh-mm-ss-tt}", mail.ReceivedTime) + ".msg");
System.Windows.Forms.MessageBox.Show(System.IO.File.Exists(RelevantDirectory[0] + "\\Email Correspondence\\Outgoing\\" + mail.SenderName + " - " + string.Format("text-{0:yyyy-MM-dd_hh-mm-ss-tt}", mail.ReceivedTime) + ".msg").ToString()); //returns True!
The MessageBox returns True, yet the file isn't actually there! The CreateDirectory code also doesn't create the directory - and I'm sure that the filepath in the program is correct. I understand from this link that this could have something to do with filesystem virtualisation. If so, how do I get around the problem?
One more point is that if I point mail.SaveAs to the Desktop folder, it saves it.
EDIT For some bizarre reason, using Path.Combine() worked. Credit to Sinatr. Thanks for your hints everyone.
The problem is in the line:
string.Format("text-{0:yyyy-MM-dd_hh-mm-ss-tt}", mail.ReceivedTime)
When converted to string it becomes somthing like : 1/1/2014 12:35:35 PM
when creating files a '/' and ':' are illegal characters , so for the minimal amount change I suggest you append a couple Replace functions at the end of your string.Format like this:
string.Format("text-{0:yyyy-MM-dd_hh-mm-ss-tt}", mail.ReceivedTime).Replace('/','-').Replace(':',' ')