My application is running on the winCE platform and needs to search the file when it initialized, but it seems winCE is very different from windows.
Step1. Get the current directory
So first, I am using a code to get a directory:
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase.ToString()) + "\\";
The path is "\Program Files\SmartDeviceProject1\".
But when I use console.write it shows "\Program Files\SmartDeviceProject1\". So it missed "\"
Step2. Trying to get all the file name in the path
FileInfo[] fileinfo = dir.GetFiles();
Step3. Use a loop and IF to identify the file exist or not.
Here is some code.
string filename = "bridgetool";
// string path = Directory.GetCurrentDirectory(); // This is not working in winCE
// Get the current path
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase.ToString()) + "\\";
Console.Write(path);
DirectoryInfo dir = new DirectoryInfo(path);
FileInfo[] fileinfo = dir.GetFiles();
foreach (FileInfo file in fileinfo)
{
if (filename == file.ToString())
{
return true;
}
}
Console.Write("Cannot find");
return false;
I got the right current path but the problem is that the path I get and path I printed out is different. I am not sure if it is a problem.
Is there any way to search the file name in the specific path?
Related
I need a library of vector files, where the same files have to be used every time. I want to load them from a folder and have the option to store new ones.
I tried having a library folder inside the WPF project that contains the files:
Solution/Project/Library/file1.dxf
I load them like this:
string currentDir = Directory.GetCurrentDirectory();
var cutOff = currentDir.LastIndexOf(#"\bin\");
var folder = currentDir.Substring(0, cutOff) + #"\Library\";
string[] filePaths = Directory.GetFiles(folder, "*.dxf");
This worked when running on the PC the project was buid, but the program crashes when the .exe is run on another PC. How do I fix this or is there a better approach to this?
Create a subfolder under Environment.SpecialFolder.ApplicationData, read the files in the library folder if it exists. If not create it and save the existing library files to it (here from resources):
string appFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = appFolder + #"\MyAppLibrary\";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
// Add existing files to that folder
var rm = Properties.Resources.ResourceManager;
var resSet = rm.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (var res in resSet)
{
var entry = ((DictionaryEntry)res);
var name = (string)entry.Key;
var file = (byte[])rm.GetObject(name);
var filePath = path + name + ".dxf";
File.WriteAllBytes(filePath, file);
}
}
// Load all files from the library folder
string[] filePaths = Directory.GetFiles(path, "*.dxf");
Thanks Jonathan Alfaro and Clemens!
I'm Currently inside a for loop which iterates through a set of folders and obtains some required values from a JSON file. I also want to get the absolute path to each of those files.
Currently I tried approaches such as
string currentDir = AppDomain.CurrentDomain.BaseDirectory; string
currentDir = Directory.GetCurrentDirectory();
Both of these gave me location to the debug file
what I want is the location of the Folder in which this file is existing rather .
Below is the code segment to which I hope to include this new code.
string rootDirectory = fbd.SelectedPath;
var foundFiles = Directory.EnumerateFiles(rootDirectory,
"server.config", SearchOption.AllDirectories);
foreach (var file in foundFiles)
{ RepositoryHomeSettingsModel repositoryHomeSettingsModel =
JsonConvert.DeserializeObject(File.ReadAllText(file));
string Name = SettingsModel.name;
}
Please find below possible ans,Do you require the same ?
var foundFiles = Directory.EnumerateFiles(rootDirectory, "*.txt", SearchOption.AllDirectories);
foreach (var file in foundFiles)
{
var folderpath= Path.GetDirectoryName(file);
//RepositoryHomeSettingsModel repositoryHomeSettingsModel = JsonConvert.DeserializeObject(File.ReadAllText(file));
//string Name = SettingsModel.name;
}
I'm writing application launcher as a Window Application in C#, VS 2017. Currently, having problem with this piece of code:
if (System.IO.Directory.Exists(extractPath))
{
string[] files = System.IO.Directory.GetFiles(extractPath);
string[] dirs = Directory.GetDirectories(extractPath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
var fileName = System.IO.Path.GetFileName(s);
var destFile = System.IO.Path.Combine(oldPath, fileName);
System.IO.File.Move(s, destFile);
}
foreach (string dir in dirs)
{
//var dirSplit = dir.Split('\\');
//var last = dirSplit.Last();
//if (last != "Resources")
//{
var fileName = System.IO.Path.GetFileName(dir);
var destFile = System.IO.Path.Combine(oldPath, fileName);
System.IO.Directory.Move(dir, destFile);
//}
}
}
I'm getting well known error
"The process cannot access the file 'XXX' because it is being used by another process."
I was looking for solution to fix it, found several on MSDN and StackOvervflow, but my problem is quite specific. I cannot move only 1 directory to another, which is Resources folder of my main application:
Here is my explanation why problem is specific:
I'm not having any issues with moving other files from parent directory. Error occurs only when loop reaches /Resources directory.
At first, I was thinking that it's beeing used by VS instantion, in which I've had main app opened. Nothing have changed after closing VS and killing process.
I've copied and moved whole project to another directory. Never opened it in VS nor started via *.exe file, to make sure that none of files in new, copied directory, is used by any process.
Finally, I've restarted PC.
I know that this error is pretty common when you try to Del/Move files, but in my case, I'm sure that it's being used only by my launcher app. Here is a little longer sample code to show what files operation I'm actually doing:
private void RozpakujRepo()
{
string oldPath = #"path\Debug Kopia\Old";
string extractPath = #"path\Debug Kopia";
var tempPath = #"path\ZipRepo\RexTempRepo.zip";
if (System.IO.File.Exists(tempPath) == true)
{
System.IO.File.Delete(tempPath);
}
System.IO.Compression.ZipFile.CreateFromDirectory(extractPath, tempPath);
if (System.IO.Directory.Exists(oldPath))
{
DeleteDirectory(oldPath);
}
if (!System.IO.Directory.Exists(oldPath))
{
System.IO.Directory.CreateDirectory(oldPath);
}
if (System.IO.Directory.Exists(extractPath))
{
string[] files = System.IO.Directory.GetFiles(extractPath);
string[] dirs = Directory.GetDirectories(extractPath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
var fileName = System.IO.Path.GetFileName(s);
var destFile = System.IO.Path.Combine(oldPath, fileName);
System.IO.File.Move(s, destFile);
}
foreach (string dir in dirs)
{
//var dirSplit = dir.Split('\\');
//var last = dirSplit.Last();
//if (last != "Resources")
//{
var fileName = System.IO.Path.GetFileName(dir);
var destFile = System.IO.Path.Combine(oldPath, fileName);
System.IO.Directory.Move(dir, destFile);
//}
}
}
string zipPath = #"path\ZipRepo\RexRepo.zip";
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
And now, my questions:
Can it be related to file types (.png, .ico, .bmp) ?
Can it be related to fact, that those resources files are being used like, as, for example .exe file icon in my main application? Or just because those are resources files?
Is there anything else what I'm missing and what can cause the error?
EDIT:
To clarify:
There are 2 apps:
Main Application
Launcher Application (to launch Main Application)
And Resources folder is Main Application/Resources, I'm moving it while I'm doing application version update.
It appeared that problem is in different place than in /Resources directory. Actually problem was with /Old directory, because it caused inifinite recurrence.
Here's my code in moving excel file to be specific..
if (Directory.GetFiles(destinationPath, "*.xls").Length != 0)
{
//Move files to history folder
string[] files = Directory.GetFiles(destinationPath); //value -- D://FS//
foreach (string s in files)
{
var fName = Path.GetFileName(s); //12232015.xls
var sourcePath = Path.Combine(destinationPath, fName);
var destFile = Path.Combine(historyPath, fName); // -- D://FS//History
File.Move(fName, destFile);
}
}
But it gets an error of
Could not find file 'D:\Project\ProjectService\bin\Debug\12232015.xls'.
Why it finds under my project not on the specific folder i set?
Thank you.
You're only using the name of the file:
var fName = Path.GetFileName(s); //12232015.xls
//...
File.Move(fName, destFile);
Without a complete path, the system will look in the current working directory. Which is the directory where the application is executing.
You should use the entire path for the source file:
File.Move(sourcePath, destFile);
Explicitly specifying the full path is almost always the best approach. Relative paths are notoriously difficult to manage.
There is an Logical error. Change
File.Move(fName, destFile);
to
File.Move(sourcePath, destFile);
as fName only contains file name and not fullpath. The file is checked in working directory.
Hello everyone and well met! I have tried a lot of different methods/programs to try and solve my problem. I'm a novice programmer and have taken a Visual Basic Class and Visual C# class.
I'm working with this in C#
I started off by making a very basic move file program and it worked fine for one file but as I mentioned I will be needing to move a ton of files based on name
What I am trying to do is move .pst (for example dave.pst) files from my exchange server based on username onto a backup server in the users folder (folder = dave) that has the same name as the .pst file
The ideal program would be:
Get files from the folder with the .pst extension
Move files to appropriate folder that has the same name in front of the .pst file extension
Update:
// String pstFileFolder = #"C:\test\";
// var searchPattern = "*.pst";
// var extension = ".pst";
//var serverFolder = #"C:\test3\";
// String filename = System.IO.Path.GetFileNameWithoutExtension(pstFileFolder);
// Searches the directory for *.pst
DirectoryInfo sourceDirectory = new DirectoryInfo(#"C:\test\");
String strTargetDirectory = (#"C:\test3\");
Console.WriteLine(sourceDirectory);
Console.ReadKey(true);>foreach (FileInfo file in sourceDirectory.GetFiles()) {
Console.WriteLine(file);
Console.ReadKey(true);
// Try to create the directory.
System.IO.Directory.CreateDirectory(strTargetDirectory);
file.MoveTo(strTargetDirectory + "\\" + file.Name);
}
This is just a simple copy procedure. I'm completely aware. The
Console.WriteLine(file);
Console.ReadKey(true);
Are for verification purpose right now to make sure I'm getting the proper files and I am. Now I just need to find the folder based on the name of the .pst file(the folder for the users are already created), make a folder(say 0304 for the year), then copy that .pst based on the name.
Thanks a ton for your help guys. #yuck, thanks for the code.
Have a look at the File and Directory classes in the System.IO namespace. You could use the Directory.GetFiles() method to get the names of the files you need to transfer.
Here's a console application to get you started. Note that there isn't any error checking and it makes some assumptions about how the files are named (e.g. that they end with .pst and don't contain that elsewhere in the name):
private static void Main() {
var pstFileFolder = #"C:\TEMP\PST_Files\";
var searchPattern = "*.pst";
var extension = ".pst";
var serverFolder = #"\\SERVER\PST_Backup\";
// Searches the directory for *.pst
foreach (var file in Directory.GetFiles(pstFileFolder, searchPattern)) {
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
// Gets the user name based on file name
// e.g. DaveSmith.pst would become DaveSmith
var userName = theFileInfo.Name.Replace(extension, "");
// Sets up the destination location
// e.g. \\SERVER\PST_Backup\DaveSmith\DaveSmith.pst
var destination = serverFolder + userName + #"\" + theFileInfo.Name;
File.Move(file, destination);
}
}
System.IO is your friend in this case ;)
First, Determine file name by:
String filename = System.IO.Path.GetFileNameWithoutExtension(SOME_PATH)
To make path to new folder, use Path.Combine:
String targetDir = Path.Combine(SOME_ROOT_DIR,filename);
Next, create folder with name based on given fileName
System.IO.Directory.CreateDirectory(targetDir);
Ah! You need to have name of file, but with extension this time. Path.GetFileName:
String fileNameWithExtension = System.IO.Path.GetFileName(SOME_PATH);
And you can move file (by File.Move) to it:
System.IO.File.Move(SOME_PATH,Path.Combine(targetDir,fileNameWithExtension)
Laster already show you how to get file list in folder.
I personally prefer DirectoryInfo because it is more object-oriented.
DirectoryInfo sourceDirectory = new DirectoryInfo("C:\MySourceDirectoryPath");
String strTargetDirectory = "C:\MyTargetDirectoryPath";
foreach (FileInfo file in sourceDirectory.GetFiles())
{
file.MoveTo(strTargetDirectory + "\\" + file.Name);
}