I have a filepath string defined like so:
string projectPath = #"G:\filepath\example\example\";
however when I debug:
projectPath = G:\\filepath\\example\\example\\
am I missing something? I thought the # was for literal string's so I don't have to escape backslashes. If I try escaping
string projectPath = "G:\\filepath\\example\\example\\";
I get the same problem, any ideas?
EDIT: Apparently this is a non-issue, my code just happens to break where projectPath is used:
string [] folders = Directory.GetDirectories(projectPath);
I guess I have an incorrect path?
EDIT 2: the issue wasn't the string, it was an access denied on the folder I tried to access. Oops!
No, the debugger shows the extra backslashes but they are not actually there.So you don't need to be worry.
Based on your edits and comments, I gather that you might benefit from using try{}catch(){} statements in your code. If it's an invalid IO operation, such an invalid path, you would be able to see it from the exception's message and avoid "crashes."
Example:
string projectPath = #"G:\filepath\example\example\";
string[] folders = null;
try
{
folders = Directory.GetDirectories(projectPath);
}
catch(Exception e)
{
Debug.WriteLine(e.Message);
}
You may also try Directory.Exists() method:
string projectPath = #"G:\filepath\example\example\";
string[] folders = null;
if (Directory.Exists(projectPath))
{
folders = Directory.GetDirectories(projectPath);
}
Although, I prefer try{}catch(){}, just in case there's a permissions issue.
Related
I am using Directory.CreateDirectory(string) method to create folders, now the problem is if the user enters string as:
"C:\folder1" then it creates the folder in the respective location, fine by me.
but if he writes
"C:\\\\\\\\\\\\\\\\\\\\\\\\\folder1" it is also navigating to the same path, creates folder and not giving any error, this is a problem for me.
So in order to solve the above mentioned problem I try to do some validation before on the path and I tried with Path.GetFullPath() and other Path methods and I see:
Path.GetFullPath("C:\\\\folder1") no exception or error
Path.GetFullPath("C:\\\folder1") exception or error
somehow when the count of backslashes are in even number no exception is thrown but when the count is in odd number then exception is thrown.
How can I achieve this simple thing that when user enters path like:
C:\folder 1 valid path
C:\\\\\\folder1 invalid path
Please let me know if further details are required
Possible solution using FolderBrowserDialog - Users will not manually input the path but rather select/create it via FolderBrowserDialog.
The below code will return all the files in a folder but you can amend it to return whatever information you need.
private void Form1_Load(object sender, EventArgs e)
{
//
// This event handler was created by double-clicking the window in the designer.
// It runs on the program's startup routine.
//
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
//
// The user selected a folder and pressed the OK button.
// We print the number of files found.
//
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
}
}
Code found here
If you want to get a proper path from that, maybe you can use the following technique (in addition to what you already have, of course, this is only to remove the repeated backslashes)
Split the path using the '\' character
Remove the empty values (you can filter here the non valid
characters, etc)
Reconstruct the path string using join with the character '\' again
Something like:
pathString = "C:\\\\\\folder1";
splitString = pathString.Split('\\');
nonEmpty = splitString.Where(x => !string.IsNullOrWhiteSpace(x));
reconstructed = string.Join("\\", nonEmpty.ToArray());
Test code here: https://dotnetfiddle.net/qwVqv8
What about sanitizing the path?
char[] separator = new char[] { System.IO.Path.DirectorySeparatorChar };
string inputPath = "C:\\\\\\\folder1";
string[] chunks = inputPath.Split(separator, StringSplitOptions.RemoveEmptyEntries);
string validPath = String.Join(new string(separator), chunks);
i have problem with my c# code, i want to list all files from mozilla user data folder, i was trying to do it with:
String dir = Directory.GetDirectories(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Mozilla\\Firefox\\Profiles\\")[0];
string[] fileEntries = Directory.GetFiles(Environment.GetEnvironmentVariable("AppData") + "\\Mozilla\\Firefox\\Profiles\\" + dir);
But when i execute this code i get error that tells me that format of this path is not supported. In error info i can see that my path is:
"C:\Users\Marcin\AppData\Roaming\Mozilla\Firefox\Profiles\4wrivbme.default"
Its because of \? I'm sure that i need this.
If I have understood correctly your code, then the second line should be just
string[] fileEntries = Directory.GetFiles(dir);
On my PC your second line gives back this path that is clearly wrong
C:\Users\steve\AppData\Roaming\Mozilla\Firefox\Profiles\C:\Users\steve\AppData.....
^^^^^
So a full fix of your code should be as this
string mozillaProfilePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"Mozilla\\Firefox\\Profiles");
string[] dirs = Directory.GetDirectories(mozillaProfilePath);
if(dirs.Length > 0)
{
string[] fileEntries = Directory.GetFiles(dirs[0]);
......
}
and, if your process the result directly here, then it is better to use Directory.EnumeratFiles instead of GetFiles (See remarks in the link posted)
.....
if(dirs.Length > 0)
{
foreach(string file in Directory.EnumerateFiles(dirs[0]))
{
.... process each file found ...
}
}
Use Path.Combine() instead of string concatenation.
I am relatively well versed in C#, having worked in Unity (game engine) for a good 5 years now, but don't go near Windows much, just a heads up if it's something stupid I've missed.
In my WPF application, I am trying to look for a file in the root application location (\bin\Debug), but I keep receiving this error when I run it.
An exception of type 'System.IO.IOException' occurred in mscorlib.dll
but was not handled in user code Additional information: The directory
name is invalid.
Hopefully someone here can see what I've done wrong, and aid me in fixing this.
I am working on this as a side project for a friend who needed some help from someone who knows c#, but I've never gone near the Windows side of things before. (It's being run in the "public MainWindow()" initializer).
InitializeComponent();
string[] filePath = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "settings.txt");
string fileContent = filePath.ToString();
string[] contentArray = fileContent.Split(':');
string contentColor;
string contentIntensity;
for (int i = 0; i < contentArray.Length; i++)
{
switch (i)
{
case 0:
{
if (contentArray[i].ToLower().Contains("color: "))
{
contentColor = contentArray[i].Replace("title: ", "");
}
if (contentArray[i].ToLower().Contains("intensity: "))
{
contentIntensity = contentArray[i].Replace("intensity: ", "");
}
break;
}
}
}
What were you thinking here?
string[] filePath = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "settings.txt");
string fileContent = filePath.ToString();
It should be written as :
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "settings.txt");
string fileContent = File.ReadAllText(filePath);
you could do something like this
var filePath = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory).
Where(name => name.Contains("settings")).ToList();
or
var filePath = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory).
Where(name => name.EndsWith(".txt")).ToList();
or return a string[]
var filePath = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory).
Where(name => name.EndsWith(".txt")).ToArray();
From MSDN
Directory.GetFiles :
Returns the names of files (including their paths) that match the
specified search pattern in the specified directory.
The method GetFiles accepts one or two parameters, a path or a path and a search pattern, the path has to be a directory !
IOException occurs when :
Path is a file name or there is a network error, and you are in the first case.
the method argument you are giving (AppDomain.CurrentDomain.BaseDirectory + "settings.txt") which is a file name not a directory, that's why you are having that exception.
So, instead of calling GetFiles on a File !! Just combine the two strings to get a file path by doing :
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "settings.txt");
I have my program setup to rename and store a file according to checkbox input. I used another stackoverflow post for my template. Only problem is when I tried setting it up for sub-folders, it never puts it in the correct folder. I have a label folder with two sub folders called L-Labels and B-Labels. The user checks which label type it is and the file gets renamed and placed in the according sub-folder. When I used breakpoint my variables are getting the correct value so I don't see what's wrong I have provided my variables and code for relocating the file. What is causing this to not put it in my sub-folder?
Varibales:
string oldPath = lblBrowseName.Text;
string newpathB = #"C:\Users\Public\Labels\B_Labels";
string newpathL = #"C:\Users\Public\Labels\L_Labels";
Method:
if (rChkBoxBizerba.Checked == true)
{
string newFileName = rtxtBoxNewVersion.Text;
FileInfo f1 = new FileInfo(oldPath);
if (f1.Exists)
{
if (!Directory.Exists(newpathB))
{
Directory.CreateDirectory(newpathB);
}
f1.CopyTo(string.Format("{0}{1}{2}", newpathB, newFileName, f1.Extension));
if (System.IO.File.Exists(lblBrowseName.Text))
System.IO.File.Delete(lblBrowseName.Text);
}
I would say this is the problem:
f1.CopyTo(string.Format("{0}{1}{2}", newpathB, newFileName, f1.Extension));
You declare your path but it doesn't have a trailing directory separator, so when you combine all the parts, as above, the actual result is invalid.
You really should use Path.Combine() to combine parts of paths together, this uses the correct directory separator and makes additional checks.
Try something like this:
// Build actual filename
string filename = String.Format("{0}{1}",newFileName, f1.Extension));
// Now build the full path (directory + filename)
string full_path = Path.Combine(newpathB,filename);
// Copy file
f1.CopyTo(full_path);
string path = Path.GetDirectoryName(
Assembly.GetAssembly(typeof(MyClass)).CodeBase);
output:
file:\d:\learning\cs\test\test.xml
What's the best way to return only d:\learning\cs\test\test.xml
file:\\ will throw exception when I call doc.Save(returnPath) ,however doc.Load(returnPath); works well. Thank you.
string path = new Uri(Assembly.GetAssembly(typeof(MyClass)).CodeBase).LocalPath;
If you want the directory of the assembly of that class, you could use the Assembly.Location property:
string path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(MyClass)).Location);
This isn't exactly the same as the CodeBase property, though. The Location is the "path or UNC location of the loaded file that contains the manifest" whereas the CodeBase is the " location of the assembly as specified originally, for example, in an AssemblyName object".
System.Uri uri = new System.Uri(Assembly.GetAssembly(typeof(MyClass)).CodeBase);
string path = Path.GetDirectoryName(uri.LocalPath);
My first approach would be like this...
path = path.Replace("file://", "");
use the substring string method to grab the file name after file:\