I'm trying make the user select a path, which the program will later on use, the reason why I want it to write it to a file, may be a little irrelevant but I see it as the simplest way for myself to handle the user wanting it to change it at anytime trough the GUI. I'm trying to what I believe is a string array converted to a normal string to use for File.Writealltext but I am failing to do so.
The code I am using is as follows:
string[] selecteddir = Directory.GetDirectories(folderBrowserDialog1.SelectedPath).ToString();
File.WriteAllText(#"/Data/storagedir.cfg", insertstringhere);
The entire strech of code(form load) is as follows.
private void savelocation_Load(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string[] selecteddir = Directory.GetDirectories(folderBrowserDialog1.SelectedPath).ToString();
File.WriteAllText(#"/Data/storagedir.cfg", insertstringhere);
}
else
{
MessageBox.Show("Something went wrong");
}
}
The error is as follows:
CS0029 "Cannot implicitly convert type 'string' to 'string[]' "
To write all the directories names into storagedir.cfg you can use WriteAllLines:
string[] selecteddir = Directory.GetDirectories(folderBrowserDialog1.SelectedPath);
File.WriteAllLines(#"/Data/storagedir.cfg", selecteddir);
^^^^^
That takes an array as second parameter.
Or use String.Join
string[] selecteddir = Directory.GetDirectories(folderBrowserDialog1.SelectedPath);
File.WriteAllText(#"/Data/storagedir.cfg", String.Join(", ", selecteddir);
If you're trying to save the selected path to storagedir.cfg:
File.WriteAllText(#"/Data/storagedir.cfg", olderBrowserDialog1.SelectedPath)
Little difficult to make out exactly what you're trying to achieve, though your problem is that you are getting a list of sub-directories with Directory.GetDirectories(folderBrowserDialog1.SelectedPath) but then calling .ToString() on it. This is throwing your error.
perhaps you don't need to store an array of directories, but only the directory that the user selected. If that is the case then you can omit that line altogether and then store the selected directory in your config.
So this:
File.WriteAllText(#"/Data/storagedir.cfg", insertstringhere);
Becomes this:
File.WriteAllText(#"/Data/storagedir.cfg", folderBrowserDialog1.SelectedPath);
Then later, when you need a list of your config directories you can read that setting from your config and get an array of directories like:
string[] dirs = Directory.GetDirectories(theStringInMyConfig);
That is the corrections:
string selecteddir = Directory.GetDirectories(folderBrowserDialog1.SelectedPath).ToString();
File.WriteAllText(selecteddir + #"\Data\storagedir.cfg", insertstringhere);
ToString() din't return aray of strings, just simple one string.
Use full path or ./ in path. Thats shy "selecteddir" you need, right?
With "#" attribute you can use a normal "\"
Ensure, thats a "Data" folder is exist. And what are you will doing, when the user select "Data" folder in dialog? Save into "...\Data" + #"\Data\storagedir.cfg" :) Affraid it will be too many "Data" folders inside "Data" folders
Related
I have a folder location corresponding to the variable "path".
In this folder, I have a lot of files, but only one called "common.build.9897ytyt4541". What I want to do is to read the content of this file, so with the following, it's working :
string text = File.ReadAllText(Path.Combine(path, "common.build.9897ytyt4541.js"));
The problem is, that the part between "build" and "js", change at each source code compilation, and I am getting a new hash, so I would like to replace the previous code, to have something working at each build, whatever the hash is, I thought to regex but this is not working :
string text = File.ReadAllText(Path.Combine(path, #"common.build.*.js"));
Thanks in advance for your help
If you know you'll only find one file you can write something like this (plus error handling):
using System.Linq;
...
var filePath = Directory.GetFiles(path, "common.build.*.js").FirstOrDefault();
string text = File.ReadAllText(filePath);
No, you need to use the exact filename with using File.ReadAllText. Instead, you need to search for the file, for this you can use Directory.GetFiles, for example:
var matches = Directory.GetFiles(path, "common.build.*.js");
if(matches.Count() == 0)
{
//File not found
}
else if(matches.Count() > 1)
{
//Multiple matches found
}
else
{
string text = File.ReadAllText(matches[0]);
}
This is a lot, I know; trying to dig myself out of a hole at work.
Basically, I have many files across multiple servers that I need to get a hold of. Right now I'm running in to two problems, 1) I can't figure out the best way to search through multiple UNC paths. 2) I'm having to search by a partial name, it's possible that there is more than one file that matches, but I only want to use the file created in the last three days.
Here is my code so far. I'm not looking for someone to write it, but I would appreciate any logistical pointers.
uncPath1 = "\\server\share\";
string partial = "2002265467";
DateTime date = Convert.ToDateTime("10/5/2015");
DirectoryInfo a = new DirectoryInfo(uncPath1);
FileInfo[] interactionlist = a.GetFiles("*" + partial + "*.*", SearchOption.AllDirectories);
foreach (FileInfo f in interactionlist)
{
string fullname = f.FullName;
Console.WriteLine(fullname);
Console.Read();
}
You mentioned that you need to find only files made in the past 3 days. Instead of using Convert.ToDateTime and hard-coding the date in, you should use DateTime.Today.AddDays( -3 ) to get the date three days before the day the program is being run.
And of course, in your finding files method, compare the dates with something like:
DateTime time = DateTime.Today.AddDays( -3 );
if ( File.GetCreationTime( filePath ) > time ) {
// Add the file
}
1) You want to make a basic function that looks for a filespec in a single folder. You already wrote that in your code above, you just need to turn it into a function with parameters UNC path and filespec. Have the function take a third parameter of List<FileInfo> to add found files to.
2) If you need to search subfolders, create a function that will search a UNC path's subfolders by calling the function you wrote in #1, then getting a list of all folders, and calling itself for each folder found (and in turn, those calls will call for sub-subfolders, etc.) This is called recursion. Have this function take a List and add all found files to the List, by passing it to your #1 function.
3) Get the root UNC paths you want to search into a List or Array and then call foreach on them passing them, the filespec, and the intially empty List to the #2 function.
So:
bool FindFiles(string uncPath, string fileSpec, List<FileInfo> found);
bool FildFilesSubfolders(string uncPath, string fileSpec, List<FileInfo> found);
string fileSpec = "whatever";
string[] uncPaths = { "abc", "def" }; // etc
List<FileInfo> found = new List<FileInfo>();
foreach (string nextPath in uncPaths)
{
if (FindFilesSubfolders(nextPath, fileSpec, found))
break;
}
foreach (FileInfo f in found)
{
string fullname = f.FullName;
Console.WriteLine(fullname);
Console.Read();
}
One final thought: if you are searching subdirs and you are worried about two UNC paths that are essentially duplicates (e.g., c:\foo and c:\foo\foo2), you can use This method to check for paths within another path.
Edit: If you find something you are looking for and want to exit early, have the functions return a boolean meaning you found what you wanted to stop early. Then use break in your loops. I've edited the code.
I want to get the last modified date and time of a file. For this I found System.IO.File.GetLastWriteTime(). If I want to use it it returns the error that I got an illegal character in my path.
I got this code:
string otherPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\test\";
private void button1_Click(object sender, EventArgs e)
{
DateTime datetime = File.GetLastWriteTime(otherPath + "*.txt"); // Here the error comes up
if (Directory.GetFiles(otherPath, #"*.txt").Any() && datetime == DateTime.Now)
{
MessageBox.Show("Folder has .txt file and was last modified today");
}
else
{
MessageBox.Show("Folder has .txt file and was not last modified today");
}
}
If I remove the * character it works. But then I can't define all files with ending .txt. Is there another way to do it? I already tried #"*.txt" but this doesn't work neither.
Suggestion appreciated :)
You cannot use a wildcard character in Path.GetLastWriteTime(as in Directory.GetFiles for example). It must be a valid path to a single file.
Use System.IO.Path.Combine to create a valid path.
string path = Path.Combine(otherPath, "FileName.txt");
DateTime datetime = File.GetLastWriteTime( path );
Since otherPath is a folder is assume that you want to use:
DateTime time = Directory.GetLastWriteTime(otherPath);
If you instead want to check if any text file in the folder was changed today:
string[] fileNames = Directory.GetFiles(otherPath, "*.txt");
if (fileNames.Any(fn => File.GetLastWriteTime(fn) >= DateTime.Today))
{
}
That's because * is a reserved character and cannot be used in a filename.
You appear to be trying to use * as a wildcard. Indeed that is why the character is reserved - so that it can be a wildcard. But you cannot use a wildcard with a function that returns information about one single file. What would you expect the function to do if multiple files matched?
I think what you probably need to do is enumerate all matching files with your wildcard, and request information about each matching file. You are looking for either Directory.GetFiles or Directory.EnumerateFiles.
I have a folder structure similar to this:
HostnameA->DateTimeA->hashdumpDateTimeA.txt
HostnameA->DateTimeB->hashdumpDateTimeB.txt
HostnameA->DateTimeC->hashdumpDateTimeC.txt
HostnameA->DateTimeD->hashdumpDateTimeD.txt
My Goal:
Given a folder(in this case HostnameA) i need to:
1) Get each hashdumpDateTime.txt filename and place it in a String array -Assumed the file always exist in all folder-
2) Generate DropDownBox using the array (I can figure this out)
3) When user selects a filename via dropdownbox, it will fill my datagridview with the
contents (I can figure this out)
So my problem really is the #1 since i don't know how to make a loop to check the filename coming from a HostnameA folder, I need to know this since the DateTime of these filenames changes
I really appreciate the future help, thanks and cheers =)
You can use Directory.GetFiles method
var files = Directory.GetFiles("directoryPath","*.txt",SearchOption.AllDirectories)
That will give you all file names.If you don't want just names for example if you want file's full path, and some other attributes (like CreationTime, LastAccessTime) use DirectoryInfo class
DirectoryInfo di = new DirectoryInfo("path");
var files = di.GetFiles("*.txt",SearchOption.AllDirectories)
That will return an array of FileInfo instances.Then use a loop and do what you want with the files.
You doesn't need to know the exact name of DirectoryName or FileName, using a for loop and a searchPattern instead.
private string[] GetFileNames(string folder)
{
var files = new List<string>();
foreach (var dateTimeFolder in Directory.GetDirectories(folder))
{
files.AddRange(Directory.GetFiles(dateTimeFolder, "hashdump*.txt"));
}
return files.ToArray();
}
I am hoping that by asking this question I find a far more effiecient method of doing what it is that I am trying to do.
To start, I have a function whose parameters look as follows:
private void exampleVoid(string filePath, params string[] sourceFile) {
// Code ...
}
**Notice: I am passing the 'sourceFile' parameters into a CodeDom method. This method throws an error if any of the parameters are null.**
My call to exampleVoid looks as follows:
exampleVoid(#"C:\test.txt",
"Some Data",
"Some More Data",
"Even more data");
Under certain cercumstances, the second string in the array (labled "Some More Data") may have to be removed and not passsed to the exampleVoid() method. So, is there some way of removing this string from the array alltogether? Keep in mind that nulling the string out will not work as an exception will be thrown.
Thank you for reading, as well as any further help.
Evan
You cannot remove the string from the array. Creating a new array that includes all other items except the one you want to include is your only option. The code is easy enough:
// Filters out the second item (zero-based index 1)
sourceFile = sourceFile.Where((s, i) => i != 1).ToArray();
I am not sure if I understand your question...
Having said that, you could try this:
string[] sourceFile;
if(condition)
sourceFile = new []{"Some Data","Even more data"};
else
sourceFile = new []{"Some Data","Some More Data","Even more data"};
exampleVoid(#"C:\test.txt", sourceFile);