Suppose I have a folder called test.
Now I pass that folder into a program and it will output a file called test.xyz in the same directory that contains the target folder.
The general logic I'm using is something like
string outDir = Path.GetDirectoryName(path);
string outName = Path.GetFileName(path).TrimEnd("\\".ToCharArray()) + ".xyz";
string outFile = Path.Combine(outDir, outName);
Which works, but it seems kind of excessive to perform so many operations just to build my new filename.
1: Can I reduce the number of Path calls to achieve my result?
2: Can I do something about the second line to avoid trimming and also avoid using that add operation?
This seems to work in my quick tests:
string outFile = Path.GetFullPath(path) + ".xyz";
Although I just realized your path may include a trailing slash already. If you can't change it to avoid that, you'll still have to include the .TrimEnd() call.
In my test, I'm using var path = #"C:\Windows\System32";.
You could use a FileInfo for that!
string path = #"C:\Windows\System32\";
FileInfo fi = new FileInfo(path);
string outFile = fi.DirectoryName + ".xyz";
works like a charm. even with trailing slash in the directory string
Related
I am having a problem where I am trying to ZIP up a file using the below code :-
Process msinfo = new Process();
msinfo.StartInfo.FileName = "msinfo32.exe";
string path = "\"" + Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + #"\test.nfo" + "\"";
string zippath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + #"\test.nfo";
MessageBox.Show(path);
msinfo.StartInfo.Arguments = #"/nfo "+path;
//msinfo.Start();
//msinfo.WaitForExit();
//MessageBox.Show("The File Has Been Saved!");
ZipFile.CreateFromDirectory(zippath, #"C:\Test.zip");
MessageBox.Show("Everything Is Done!");
The error that is coming is that the Folder path is not valid. I also tried by including quotation marks in the Zippath variable but it did not work.
PS - My machine name has 3 words so it has got spaces as well. Help is appreciated ^_^
The first argument of ZipFile.CreateFromDirectory should be a path of a directory, not a file (test.nfo in this case).
If you want compress the whole directory (e.g. the Desktop dir) then omit the "test.nfo" from the path, like this:
string zippath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
If you want to create a zip archive from only one file then use the ZipFileExtensions.CreateEntryFromFile.
One more thing: when you want to build a path from two or more components use the Path.Combine method instead of simple string concatenation. It can spare you from a lot of pain (like adding path separator characters).
I have some temporary files in Temporary Internet file folder i need copy them to my folder,i see the file in folder but function File.Exists no.
My function
string InternetTempPath= Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
string TempFilePath = Path.Combine(InternetTempPath, "MyFile.pdf");
bool Isfile = System.IO.File.Exists(TempFilePath);
don't see the files that i am looking for.
Files in Temporary Internet file folder do not have names they can't even be renamed,I think i need to look files by Internet Adress,or Last Checked.They not like ordinary files.
How can i find this files?
Are you missing the file extension?
Your file is probably "MyfileName.txt" not just "MyfileName".
Try adding the file extension and seeing if that works...
string TempFilePath= Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
TempFilePath+="MyfileName.txt";
bool Isfile = System.IO.File.Exists(TempFilePath);
P.S. appending strings is not recommended in C# the way you're using +=. If these were normal strings I'd recommend using a StringBuilder to combine them, as you're dealing with Paths, try using Path.Combine:
string TempFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), "MyfileName.txt");
bool Isfile = System.IO.File.Exists(TempFilePath);
Solution 1:
You need to add backward slash after the Temparary internet folder path.
TempFilePath += "\\myfile.txt";
Solution 2: (Recommended)
You can use Path.Combine() to combine the paths as below:
string newpath = Path.Combine(TempFilePath,"myfile.txt");
The problem is most likely the miss of slashes. You should use Path.Combine instead of concatenating the file path yourself:
string TempFilePath = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
string filePath = Path.Combine(TempFilePath, "MyfileName");
bool Isfile = System.IO.File.Exists(filePath);
There's a hidden folder inside that location called Content.IE5, and that will contain several randomly named folders with the actual temporary internet files inside them.
var path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache),
"Content.IE5");
Here is answer
I wrote a simple console tool that reads a file and then writes something out. I intend to just drag and drop files and then out pops the output in the same directory as the input file.
All of the testing works, and when I call it from command-line, everything comes out as expected. However, when I tried dragging and dropping it in explorer, no files were created.
I did a search through the system and found that they were all dumped at Documents and Settings under my user folder, and when I printed out the full path that's what it said.
Which is weird. Wouldn't Path.GetFullPath return the absolute path of the input file? Instead it looks like it just combined that user directory path to the input's filename.
EDIT: here's the code. I feel like I've made a logic error somewhere but can't seem to see it.
filename = System.IO.Path.GetFileName(args[i]);
abspath = Path.GetFullPath(filename);
dirpath = Path.GetDirectoryName(abspath);
....
Console.WriteLine(dirpath);
Path.GetFullPath should return the absolute path of the path string you pass in.
Path.GetFileName(string path) only returns the filename and extension of the file you pass in. For example, System.IO.Path.GetFileName("C:\SomeDirectory\Test.txt"); would just return "Test.txt". You'll want to use the Path.GetDirectoryName to get the path of your input file, like so:
string inputDirectory = System.IO.Path.GetDirectoryName(args[i]);
Alternately, you can use the FileInfo class to retrieve a bunch more information about your input file. For example:
// Assuming args[i] = "C:\SomeDirectory\Test.txt"
FileInfo inputFile = new FileInfo(args[i]);
string inputDirectory = inputFile.DirectoryName; // "C:\SomeDirectory"
string inputFileName = inputFile.Name; // "Test.txt"
string fullInputFile = inputFile.FullName; // "C:\SomeDirectory\Test.txt"
string slink = "\\README.TXT";
string ipath = "C:\\Users\\Crystal\\Documents\\Visual Studio 2010\\Projects\\workspace\\workspace\\bin\\Debug";
string test = lpath+"\\workspace\\"+slink;
string test1 = "C:\\Users\\Crystal\\Documents\\Visual Studio 2010\\Projects\\workspace\\workspace\\bin\\Debug\\workspace\\README.TXT";
string ftpfullpath = myUri.ToString();
WebClient request = new WebClient();
FileStream file = File.Create(#test);
if i write FileStream file = File.Create(#test); i get error illegal characters.
if i write FileStream file = File.Create(#test1); it works!
i think something is wrong with gluing multiple string path values. i've tried also Path.Combine but also doesn't work
In your third line of code, you've used lpath instead of ipath - i am assuming that's a typo
Use this:
string resultPath= Path.Combine(p1, p2);
MSDN Reference
Taking it that lpath is a typo for ipath, the latter adds an extra slash (or set of slashes, depending on the context) before README.TXT.
That is to say,
\\workspace\\README.TXT
becomes,
\\workspace\\\\README.TXT
You're writing "..\\" + "\\...".
A path cannot have two consecutive \s.
The problem is your either your slink or your test. The code you have ends up with the following path:
C:\Users\Crystal\Documents\Visual Studio 2010\Projects\workspace\workspace\bin\Debug\workspace\\README.TXT
Notice the double slash before README.TXT?
This is caused because slink becomes:
\README.TXT
Then you are trying to combine that with:
C:\Users\Crystal\Documents\Visual Studio 2010\Projects\workspace\workspace\bin\Debug\workspace\
You can do 1 of 2 things to fix the problem:
Remove the \\ from the slink
Remove the trailing \\ from the "\\workspace\\" when you try to combine them
I would suggest option 1 - it clearly separates the filename from the path of the file. Having the \\ preceding the file implies that the filename also has its path info
I'm trying to create a folder on the directory where the .exe file is and save a picture in that folder.
Right now that folder doesn't exist so I'd like to be created. Here's the code I have:
public void SavePictureToFileSystem(string path, Image picture)
{
string pictureFolderPath = path + "\\" + ConfigurationManager.AppSettings["picturesFolderPath"].ToString();
picture.Save(pictureFolderPath + "1.jpg");
}
The Image isn't being saved to the pictureFolderPath but to the path variable. What do I need to accomplish this?
Thanks for the help! This is what I ended up with:
public void SavePictureToFileSystem(string path, Image picture)
{
var pictureFolderPath = Path.Combine(path, ConfigurationManager.AppSettings["picturesFolderPath"].ToString());
if (!Directory.Exists(pictureFolderPath))
{
Directory.CreateDirectory(pictureFolderPath);
}
picture.Save(Path.Combine(pictureFolderPath, "1.jpg"));
}
I suspect your problem is that ConfigurationManager.AppSettings["picturesFolderPath"].ToString() returns a folder-path that is empty or, more likely, does not end with a trailing back-slash. This would mean that the final constructed path would end up looking like c:\dir1.jpg rather than c:\dir\1.jpg, which is what I think you really want.
In any case, it's much better to rely onPath.Combinethan to try to deal with the combining logic yourself. It deals with precisely these sorts of corner-cases, plus, as a bonus, it's platform-independent.
var appFolderPath = ConfigurationManager.AppSettings["picturesFolderPath"]
.ToString();
// This part, I copied pretty much verbatim from your sample, expect
// using Path.Combine. The logic does seem a little suspect though..
// Does appFolder path really represent a subdirectory name?
var pictureFolderPath = Path.Combine(path, appFolderPath);
// Create folder if it doesn't exist
Directory.Create(pictureFolderPath);
// Final image path also constructed with Path.Combine
var imagePath = Path.Combine(pictureFolderPath, "1.jpg")
picture.Save(imagePath);
I suspect ConfigurationManager.AppSettings["picturesFolderPath"].ToString() might be empty, so the pictureFolderPath variable is only being set to the path value. Make sure it is set properly and the value is being returned. Put a breakpoint on that line and check it in the Watch/Immediate windows.
You could try to create the directory first:
Directory.CreateDirectory(pictureFolderPath);