Checking to see File exists is not working - c#

I am trying to check to see if the file exists if it doesn't leave the textbox blank! it doesn't work
string[] filePaths = Directory.GetFiles(#"C:\TwinTable\LeftTableO0201", "*.*");
if (!File.Exists(filePaths.ToString()))
{
TboxLeftTable.Text = "";
}
else
{
TboxLeftTable.Text = System.IO.Path.GetFileName(filePaths[0]);
}

Well, one problem you have is that you are just trying to use ToString() on an array. Since Directory.GetFiles() returns an array of file names, you need to iterate over those files and check them one at a time. Something like this:
string[] filePaths = Directory.GetFiles(#"C:\TwinTable\LeftTableO0201", "*.*");
foreach (string curFilePath in filePaths)
{
if (!File.Exists(curFilePath))
{
TboxLeftTable.Text = "";
}
else
{
TboxLeftTable.Text = System.IO.Path.GetFileName(curFilePath);
}
}

Once your code is fixed you still have weird logic. If we take your logic and spell it out in a sentence it reads like this:
Get a list of files from a folder, then immediately check to see if the file(s) in that folder exist
I think what you want to do instead is:
Get a list of files from a folder, if one exists display the very first one's name in a textbox, if it does not, display nothing
If I am right, then your code would look like this:
// Gets all string file paths in a folder
// then grabs the first one, or null if there are none
string filePath = Directory.GetFiles(#"C:\TwinTable\LeftTableO0201", "*.*").FirstOrDefault();
// if the path is not null, empty or whitespace
if(!string.IsNullOrWhiteSpace(filePath)
{
// then get the filename and put it in the textbox
TboxLeftTable.Text = Path.GetFileName(filePath);
}
else
{
// There were no files in the folder so make the textbox empty
TboxLeftTable.Text = string.Empty;
}

This is the working code. Thanks for the help!
string[] filePaths = Directory.GetFiles(#"C:\TwinTable\LeftTableO0201", "*.*");
if (filePaths.Length > 0)
TboxLeftTable.Text = System.IO.Path.GetFileName(filePaths[0]);

Related

Convert files following the order of a list C#

I need to convert images(like .jpg) to PDF files for an assignment for school. I have a ListBox where I put the pages of the PDF file, so the user can reorder the list and convert the files in that order.
I have the files in a temporary folder in order to get the files there to convert them to PDF.
My problem here is : how do I convert the files with the order that the user had chosen?
I already searched and I tried to do a Class with the strings ID and Name so i get the ID from the item in the ListBox and change it on a new list. And i think after, I do a foreach() loop where I get the files from the temporary folder and merge them in a new PDF file, but to do in the order I want, I think I have to compare the name of the file with the name in the list and, if it matches, convert and add it, if not, pass to the next file.
But I don't know how to do it.
Can please someone help me getting this right?
Thanks in advance!
I'm sending my code to:
//the open files button
private void proc2_Click(object sender, EventArgs e)
{
OpenFileDialog dialogo = new OpenFileDialog();
dialogo.Title = "Search files";
dialogo.InitialDirectory = #"E:\";
dialogo.Filter = "Images (.bmp,.jpg,.png,.tiff,.tif) |*.bmp;*.jpg;*.png;*tiff;*tif|All of the files (*.*)|*.*";
DialogResult resposta = dialogo.ShowDialog();
if (resposta == DialogResult.OK)
{
string caminhoCompleto = dialogo.FileName;
caminho2 = dialogo.SafeFileName;
caminhotb2.Text = caminhoCompleto;
string fish = "";
string path = #"C:\temporario";
if(Directory.Exists(path))
{
fish=Path.Combine(path, caminho2);
}
else
{
Directory.CreateDirectory(path);
fish = Path.Combine(path, caminho2);
}
File.Create(fish);
listaimg.Items.Add(caminho2);
}
}
public string[] GetFilesImg4() //jpg files
{
if (!Directory.Exists(#"C:\temporario"))
{
Directory.CreateDirectory(#"C:\temporario");
}
DirectoryInfo dirInfo = new DirectoryInfo(#"C:\temporario");
FileInfo[] fileInfos4 = dirInfo.GetFiles("*.jpg");
foreach (FileInfo info in fileInfos4)
{
if (info.Name.IndexOf("protected") == -1)
list4.Add(info.FullName);
}
return (string[])list4.ToArray(typeof(string));
}
If both actions happen in the same process, you can just store the list of file names in memory (and you already do add them to listaimg):
public string[] GetFilesImg4() //jpg files
{
string tempPath = #"C:\temporario";
if (!Directory.Exists(tempPath))
{
foreach (string filename in listimga.Items)
{
if (!filename.Contains("protected"))
list4.Add(Path.Combine(tempPath, filename);
}
}
return (string[])list4.ToArray(typeof(string));
}
if these are different processes then you can just dump content of your listimga at some point and then read it from the same file. In the example below I store it to file named "order.txt" in the same directory, but logic may be more complicated, such as merging several files with a timestamp and such.
// somewhere in after selecting all files
File.WriteAllLines(#"c:\temporario\order.txt", listimga.Items.Select(t=>t.ToString()));
public string[] GetFilesImg4() //jpg files
{
string tempPath = #"C:\temporario";
if (!Directory.Exists(tempPath))
{
var orderedFilenames = File.ReadAllLines(Path.Combine(tempPath, "order.txt")); // list of files loaded in order
foreach (string filename in orderedFilenames)
{
if (!filename.Contains("protected"))
list4.Add(Path.Combine(tempPath, filename);
}
}
return (string[])list4.ToArray(typeof(string));
}
it's also a good idea to examine available method on a class, such as in this case string.IndexOf(s) == -1 is equivalent to !string.Contains(s) and the latter is much more readable at least for an English speaking person.
I also noticed that your users have to select documents one by one, but FileOpen dialogs allow to select multiple files at a time, and I believe it preserves the order of selection as well.
If order of selection is important and file open dialogs don't preserve order or users find it hard to follow you can still use multiple file selection open dialog and then allow to reorder your listimga list box to get the order right.

How to find Full Path from a given 'part of string path' using C#

I've a part of a string path: "\MVVM\MyFirstTest2016\MyFirstTest\bin\Debug\MyFirstTest.exe"
I want to search the above path in C: and need to get the complete full path of the directory.
I tried with Path.GetFullPath("") and other in-built methods but didnt get complete full path.
Here's the code:
The sourceDir will be the full path.
string defaultFolder = System.AppDomain.CurrentDomain.BaseDirectory;
string navigateToFolder = "\\MVVM\\MyFirstTest2016\\MyFirstTest\\bin\\Debug\\MyFirstTest.exe";
string sourceDir = Path.Combine(defaultFolder, navigateToFolder);
It sounds like your problem is similar to this question. You've got a partial path, but no idea where it is on this drive. The naive approach would be as follows.
You're first step would be to start at the root of the drive, and get the list of directories:
string[] dirs = Directory.GetDirectories(#"c:\", "*");
You'd then check if any of these strings matched the first directory of your root path (MVVM). If it does, you'd go into that folder and check if it contained the next directory. If it does, check the next and next, etc. until you've exhausted the path.
If not, you'd iterate over the directories, and run the same logic: get the directories, check if any match your first folder, etc.
So a bit of pseudo code would look like:
string directoryPath = "\MVVM\MyFirstTest2016\MyFirstTest\bin\Debug\MyFirstTest.exe"
string[] splitPath = directoryPath.split("\")
check("c:\")
public void check(string directory)
string[] directories = Directory.GetDirectories(#directory, "*")
if(checkDirectories(directories, splitPath))
// Success!
else
for(string subDirectory : directories)
string newDirectory = Path.combine(directory, subDirectory)
check(newDirectory)
public boolean checkDirectories(string[] directories, string[] splitPath)
// Horrible, but just for example - finding the file at the end
if(splitPath.size == 1)
// Get file list in current directory and check the last part of splitPath
if(directories.contains(splitPath[0])
// Recursively call checkDirectories with the sub directories of this folder, an splitPath missing the first item. This can be done using Array.Copy(splitPath, 1, newArray, 0)
Obviously that's nowhere near runnable, but it should give you the basic idea. The other question I linked earlier also has an accepted answer which will help more.
You could iterate over all directories and check if the sub directory is available.
The normal Directory.EnumerateDirectories may throw a UnauthorizedAccessException which stops the process of finding the directory.
So you could write your own EnumerateDirectories as shown below.
The example provided will return the folders found.
void Main()
{
string path = #"temp\A\B";
var parts = path.Split(new [] { Path.DirectorySeparatorChar });
var rootPath = "c:\\";
foreach(var result in DirectoryEx.EnumerateDirectories(rootPath, parts.First()))
{
var checkPath = Path.Combine(result, String.Join(""+Path.DirectorySeparatorChar, parts.Skip(1).ToArray()));
if (Directory.Exists(checkPath))
Console.WriteLine("Found : " + checkPath);
}
}
public class DirectoryEx
{
public static IEnumerable<string> EnumerateDirectories(string dir, string name)
{
IEnumerable<string> dirs;
// yield return may not be used in try with catch.
try { dirs = Directory.GetDirectories(dir); }
catch(UnauthorizedAccessException) { yield break; }
foreach (var subdir in dirs)
{
if(Path.GetFileName(subdir).Equals(name, StringComparison.OrdinalIgnoreCase))
yield return subdir;
foreach(var heir in EnumerateDirectories(subdir, name))
yield return heir;
}
}
}
In my case results in :
Found : c:\dev\temp\A\B
Found : c:\Temp\A\B

Can't add files to listbox...READ

I'm using a code to show all startup items in listbox with environment variable "%appdata%
There is some errors in this code that I need help with....
Check code for commented errors
Is there any other solution but still using %appdata%?
This is the code:
private void readfiles()
{
String startfolder = Environment.ExpandEnvironmentVariables("%appdata%") + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
foldertoread(startfolder);
}
private void foldertoread(string folderName)
{
FileInfo[] Files = folderName.GetFiles("*.txt"); // HERE is one error "Getfiles"
foreach (var file in Directory.GetFiles(folderName))
{
startupinfo.Items.Add(file.Name); // here is another error "Name"
}
}
This line won't work because folderName is a string (and does not have a GetFiles method):
FileInfo[] Files = folderName.GetFiles("*.txt");
The second error is occurring because the file variable is a string containing the filename. You don't need to call file.Name, just try the following:
startupinfo.Items.Add(file);
I don't think you need the following line:
FileInfo[] Files = folderName.GetFiles("*.txt");
The foreach loop will generate what you need.
Secondly, the file variable is a string, so rather than calling:
startupinfo.Items.Add(file.Name);
...call instead:
startupinfo.Items.Add(file);
Finally, instead of a var type for your loop, you can use a string, and you can specify the file type filter:
foreach (string fileName in Directory.GetFiles(folderName, "*.txt"))
The string object doesn't have a GetFiles() method. Try this:
string startfolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
string[] files = Directory.GetFiles(startfolder, "*.txt");
foreach (string file in files)
{
startupinfo.Items.Add(Path.GetFileNameWithoutExtension(file));
}
Path.GetFileNameWithoutExtension(file) returns just the file name instead of full path.

Find a file with particular substring in name

I have a dirctory like this "C:/Documents and Settings/Admin/Desktop/test/" that contain a lot of microsoft word office files. I have a textBox in my application and a button. The file's name are like this Date_Name_Number_Code.docx. User should enter one of this options, my purpose is to search user entry in whole file name and find and open the file.
thank you
string name = textBox2.Text;
string[] allFiles = System.IO.Directory.GetFiles("C:\\");//Change path to yours
foreach (string file in allFiles)
{
if (file.Contains(name))
{
MessageBox.Show("Match Found : " + file);
}
}
G'day,
Here's the approach I used. You'll need to add a textbox (txtSearch) and a button (cmdGo) onto your form, then wire up the appropriate events. Then you can add this code:
private void cmdGo_Click(object Sender, EventArgs E)
{
// txtSearch.Text = "*.docx";
string[] sFiles = SearchForFiles(#"C:\Documents and Settings\Admin\Desktop\test", txtSearch.Text);
foreach (string sFile in sFiles)
{
Process.Start(sFile);
}
}
private static string[] SearchForFiles(string DirectoryPath, string Pattern)
{
return Directory.GetFiles(DirectoryPath, Pattern, SearchOption.AllDirectories);
}
This code will go off and search the root directory (you can set this as required) and all directories under this for any file that matches the search pattern, which is supplied from the textbox. You can change this pattern to be anything you like:
*.docx will find all files with the extention .docx
*foogle* will find all files that contain foogle
I hope this helps.
Cheers!
You can use Directory.GetFiles($path$).Where(file=>file.Name.Contains($user search string$).
Should work for you.
You can use the Directory.GetFiles(string, string) which searches for a pattern in a directory.
So, for your case, this would be something like:
string[] files =
Directory.GetFiles("C:/Documents and Settings/Admin/Desktop/test/",
"Date_Name_Number_Code.docx");
Then look through the files array for what you are looking for.
if you need info about the files instead of content:
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

Rename image files on server directory

I need some help in renaming some images in a directory located at /images/graphicsLib/.
All image names in /graphicsLib/ have naming convention that looks like this:
400-60947.jpg. We call the "400" part of the file the prefix and we call the "60957" part the suffix. The entire file name we call the sku.
So if you saw the contents of /graphicLib/ it would look like:
400-60957.jpg
400-60960.jpg
400-60967.jpg
400-60968.jpg
402-60988.jpg
402-60700.jpg
500-60725.jpg
500-60733.jpg
etc...
Using C# & System.IO , what is an acceptable way to rename all image files base on the prefix of the file name? Users need to be able to enter in the current prefix, see all images in the /graphicsLib/ that match, then enter in the new prefix to have all those files renamed with the new prefix. Only the prefix of the file gets renamed, the rest of the file name needs to be unchanged.
What I have so far is:
//enter in current prefix to see what images will be affected by
// the rename process,
// bind results to a bulleted list.
// Also there is a textbox called oldSkuTextBox and button
// called searchButton in .aspx
private void searchButton_Click(object sender, EventArgs e)
{
string skuPrefix = oldSkuTextBox.Text;
string pathToFiles = "e:\\sites\\oursite\\siteroot\\images\graphicsLib\\";
string searchPattern = skuPrefix + "*";
skuBulletedList.DataSource = Directory.GetFiles(pathToFiles, searchPattern);
skuBulletedList.DataBind();
}
//enter in new prefix for the file rename
//there is a textbox called newSkuTextBox and
//button called newSkuButton in .aspx
private void newSkuButton_Click(object sender, EventArgs e)
{
//Should I loop through the Items in my List,
// or loop through the files found in the /graphicsLib/ directory?
//assuming a loop through the list:
foreach(ListItem imageFile in skuBulletedList.Items)
{
string newPrefix = newSkuTextBox.Text;
//need to do a string split here?
//Then concatenate the new prefix with the split
//of the string that will remain changed?
}
}
You could look at string.Split.
Loop over all files in your directory.
string[] fileParts = oldFileName.Split('-');
This will give you an array of two strings:
fileParts[0] -> "400"
fileParts[1] -> "60957.jpg"
using the first name in your list.
Your new filename then becomes:
if (fileParts[0].Equals(oldPrefix))
{
newFileName = string.Format("(0)-(1)", newPrefix, fileParts[1]);
}
Then to rename the file:
File.Move(oldFileName, newFileName);
To loop over the files in the directory:
foreach (string oldFileName in Directory.GetFiles(pathToFiles, searchPattern))
{
// Rename logic
}
Actually you should iterate each of the files in the directory and rename one by one
To determine the new file name, you may use something like:
String newFileName = Regex.Replace("400-60957.jpg", #"^(\d)+\-(\d)+", x=> "NewPrefix" + "-" + x.Groups[2].Value);
To rename the file, you may use something like:
File.Move(oldFileName, newFileName);
If you are not familiar with regular expressions, you should check:
http://www.radsoftware.com.au/articles/regexlearnsyntax.aspx
And download this software to pratice:
http://www.radsoftware.com.au/regexdesigner/

Categories