Moving files to corresponding folder [duplicate] - c#

This question already has an answer here:
Moving files using SSIS and Script Component
(1 answer)
Closed 4 years ago.
I'm using C# language for finding certain files and moving them to corresponding folder. I'm using this code bellow, but files that I'm getting lately cannot be read with this code. Before name of the file would be for example "File_20141120", but files that I'm getting now are named, for example: ABC (222), ACD (2), DES (33), so I need to write a code that will read numbers in parentheses and move it to folder with the same number.
The code I'm using right now:
public void Main()
{
string filename;
string datepart;
bool FolderExistFlg;
filename = Dts.Variables["User::FileName"].Value.ToString();
datepart = (filename.Substring(filename.Length - 12)).Substring(0, 8);
FolderExistFlg = Directory.Exists(Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + datepart);
if (!FolderExistFlg)
{
Directory.CreateDirectory(Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + datepart);
}
File.Move(Dts.Variables["SourceFolder"].Value.ToString() + "\\" + filename,
Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + datepart + "\\" + filename);
Dts.TaskResult = (int)ScriptResults.Success;
}
#region ScriptResults declaration
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}

SSIS is optimized for the task you are performing. If we assume that all files in the source folder need to be moved, then place the file task in a for each loop and parameterize the source and destination variables.
Create five variables:
SourceFolder
DestinationFolder
FileName
SourceFileNameWithPath = SourceFolder + "\" + FileName
DestinationFileNameWithPath = DestinationFolder + "\" + FileName
Use the ForEach loop to loop over the SourceFolder and read in each file name (select File Name and Extension) into the FileName variable (note: set FileSpec to either . or *.) . In the File Task, set the source variable to SourceFileNameWithPath and the destination variable to DestinationFileNameWithPath.
The File System Task should be Rename File.
https://www.tutorialgateway.org/move-multiple-files-using-file-system-task-in-ssis/

It sounds like you're asking how to extract the folder name from between the two parens (). If that's the case, a simple RegEx will work for you:
// Extracts only the number between the parens
// E.g. Filename: aaa (333)
// Output: 333
var folderNumber = Regex.Match(
filename,
#"\(([^)]*)\)").Groups[1].Value;

Related

Get File Extension C#

I have a dropdown with list of file names. When a file name is selected in the dropdown I do the following
string filename = ddl.SelectedItem.Text;
string path = "F:\\WorkingCopy\\files\\" + filename +".docx";
DownloadFile(path,filename);
In the file folder files may contain any extension . Since i have hard coded ".docx" in string path everything works fine. But I need to get the extension of the file name with the ddl.SelectedItem.Text alone. Can you tell me how to do this?
Things I have
1.) File name without extension in
string filename = ddl.SelectedItem.Text;
2.) Path where the file is located
string path = "F:\\WorkingCopy\\files\\" + filename
I am trying to get the file extension with these . Can any one suggest on this?
You can use Directory.EnumerateFiles() like this:
string path = "F:\\WorkingCopy\\files\\";
string filename = ddl.SelectedItem.Text;
string existingFile = Directory.EnumerateFiles(path, filename + ".*").FirstOrDefault();
if (!string.IsNullOrEmpty(existingFile))
Console.WriteLine("Extension is: " + Path.GetExtension(existingFile));
Directory.EnumerateFiles searches the path for files like filename.*. Path.GetExtension() returns the extension of the found file.
In general, I prefer to use EnumerateFiles() instead of GetFiles because it returns an IEnumerable<string> instead string[]. This suggests that it only returns the matching files as needed instead searching all matching files at once. (This doesn't really matter in your case, just a general note).
Use the Directory.GetFiles() method. Something like this
string[] files = Directory.GetFiles("F:\\WorkingCopy\\files\\", filename+".*");
This should get you an array of filenames with the same filename but different extensions. If you have only one, then you can always use the first one.
You can use Directory.GetFiles Method:
string result = Directory.GetFiles(path, filename + ".*").FirstOrDefault();
see here
here " * " is the WildCard and will search for the Filename starts with YourFileName.
you can achieve that with followed by line
try
{
var extensions = new List<string>();
var files = Directory.GetFiles("F:\\WorkingCopy\\files\\", filename + ".*", System.IO.SearchOption.TopDirectoryOnly);
foreach (var tmpfile in files)
extensions.Add(Path.GetExtension(tmpfile));
}
catch (Exception ex)
{
throw ex;
}
will this help you?
You can simply split them by dot, For example, try this code
string folder = #"F:\\WorkingCopy\\files\\";
var files = System.IO.Directory.GetFiles(folder, filename + ".*");
if (files.Any())
{
string ext = System.IO.Path.GetExtension(files.First()).Substring(1);
}
This code gives me result that the extension for this is txt file.

Can't move multiple files in a directory

I am trying to move multiple files in a directory to an archive sub folder. I used a foreach loop to do the idea. Unfortunately, It can only move a file if there is only one file in the directory. But when I put multiple in the directory the Directory.move(); won't work. Can anyone help me?
static string antJsonSerializer(){
#region KDI SALES
string[] allfiles = Directory.GetFiles(#"C:\xml\"); // Put all file names in root directory into array.
string sourceDirectory = #"C:\xml\";
string destinationDirectory = #"C:\xml\Archive\";
// Check if directories are existing -- Working
bool xmlRoot = System.IO.Directory.Exists(sourceDirectory);
if (!xmlRoot) System.IO.Directory.CreateDirectory(sourceDirectory);
bool xmlArchive = System.IO.Directory.Exists(destinationDirectory);
if (!xmlArchive) System.IO.Directory.CreateDirectory(destinationDirectory);
AntHelpers drone = new AntHelpers();
foreach (string name in allfiles)
{
try
{
drone.xmltosql(#name.Trim());
//File.Move(#name, destinationDirectory + (DateTime.Now.Year).ToString() + (DateTime.Now.Month).ToString().PadLeft(2, '0') + (DateTime.Now.Day).ToString().PadLeft(2, '0') + (DateTime.Now.Hour).ToString().PadLeft(2, '0') + ".html"); //Not working
Directory.Move(#name, destinationDirectory + (DateTime.Now.Year).ToString() + (DateTime.Now.Month).ToString().PadLeft(2, '0') + (DateTime.Now.Day).ToString().PadLeft(2, '0') + (DateTime.Now.Hour).ToString().PadLeft(2, '0') + ".html");
//Directory.Move(sourceDirectory, destinationDirectory); //Not working
}
catch (Exception e)
{
//Console.WriteLine("Main Process Catch ERR: " + e.Message);
//ErrLogtoDB(string TRNTYPE, string extserial, string texttowrite, string logfilename)
AntHelpers.ErrLogtoDB("SALES", #name, "Ant JSON Serializer Failed: " + e.Message,
"LeafCutterLogFile_JSONSerializer_" + (DateTime.Now.Year).ToString() + (DateTime.Now.Month).ToString().PadLeft(2, '0') + (DateTime.Now.Day).ToString().PadLeft(2, '0') + (DateTime.Now.Hour).ToString().PadLeft(2, '0') + ".html");
}
//drone.ExtractSQLSendAntHill(); //For testing: OFF
#endregion
return " !!!! Work Complete !!!! ";
}
You are trying to save a file with year + month + day + hour.html as "NAME". If multiple files are there, then how can you save it with same file name? Instead you should add seconds and/or milliseconds, or use something else to distinguish the file and make it a unique name. Otherwise, take file name without the extension then add year, month, day, and hour. That is why you are not able to move multiple files at a time, because when try to move the second file an exception will be thrown say "unable to move an existing file."
Directory.Move takes a source and destination directory, not a file path. Try this:
Directory.Move(sourceDirectory, destinationDirectory);
Also, it can be run at the very end - after the foreach loop.

Renaming files programmatically, decrementing

I have a folder with a certain number of text files named 1.txt, 2.txt 3.txt etc.
My goal is that when one of them is deleted, to rename any of the files greater than the file deleted down one.
Ex. if 1.txt is deleted, 2 should be renamed to 1, and 3 renamed to 2, so on and so forth.
Here is my attempt so far:
private void deletequestionbtn_Click(object sender, EventArgs e)
{
string fileDel = testfolderdialog.SelectedPath.ToString() + #"\" + questionCountint.ToString() + ".txt";
DirectoryInfo d = new DirectoryInfo(testfolderdialog.SelectedPath.ToString() + #"\");
File.Delete(fileDel);
questionCountint++;
foreach (var file in d.GetFiles("*.txt"))
{
string fn = file.Name;
string use = fn.Replace(".txt", "");
int count = int.Parse(use);
if (count > questionCountint)
{
File.Move(fileDel, testfolderdialog.SelectedPath.ToString() + #"\" + questionCountint--.ToString() + ".txt");
}
}
}
The issue is occuring on the File.Move line, it's saying it cannot locate the file in fileDel, though I am incrementing questionCountint after deleting fileDel
Am I approaching this the wrong way? Is there a more effective way to write the foreach statement? I only want to rename the files greater than the file deleted.
Where am I going wrong?
The problem is that you are trying to rename fileDel, which is the file that you have deleted. You should rename file instead.
However, you will quickly run into the next problem. If you don't get the files in the exact order that you expect, you will try to rename a file to a name that already exists.
If the GetFiles method returns the files in the order "3.txt", "2.txt", you will first try to rename "3.txt" to "2.txt", but "2.txt" already exists.
You should first loop through the files and gather all files that should be renamed. Then you should sort the files on the number so that you can rename them in the correct order.
As the format of the file names is so simple to recreate from the number, you can just get the numbers in a list:
List<int> files = new List<int>();
foreach (var file in d.GetFiles("*.txt")) {
string fn = file.Name;
string use = fn.Replace(".txt", "");
int count = int.Parse(use);
if (count > questionCountint) {
files.Add(count);
}
}
string path = testfolderdialog.SelectedPath.ToString();
foreach (int count in files.Ordery(n => n)) {
File.Move(String.Concat(path, count.ToString() + ".txt"), String.Concat(path, (count - 1).ToString() + ".txt");
}

how to concatenate value of dropdown list

I have three dropdown lists. From these three I have to select various path to retrieve one folder. The problem is path can't retrieve the folder and give error can't find a part of path. My code for that is.
protected void Btn_Load_Click1(object sender, EventArgs e)
{
string _username = ConfigurationManager.AppSettings["ImpersonatedUserName"].ToString();
string _password = ConfigurationManager.AppSettings["ImpersonatedPassword"].ToString();
string _domain = ConfigurationManager.AppSettings["ImpersonatedDomain"].ToString();
Impersonation objImpersonation = new Impersonation();
if (objImpersonation.impersonateValidUser(_username, _domain, _password))
{
string PathFecha = ConfigurationManager.AppSettings.ToString() + "\\Convert.ToString(Drp_List1.SelectedItem)\\Convert.ToString(Drp_List2.SelectedItem)\\Convert.ToString(Drp_List3.SelectedItem)\\";
string[] files = System.IO.Directory.GetFiles(PathFecha);
foreach (string filename in files)
{
ListBox1.Items.Add(new ListItem(System.IO.Path.GetFileName(filename), filename));
}
}
}
You are not converting the paths properly.
Change this line:
string PathFecha = ConfigurationManager.AppSettings.ToString() + "\\Convert.ToString(Drp_List1.SelectedItem)\\Convert.ToString(Drp_List2.SelectedItem)\\Convert.ToString(Drp_List3.SelectedItem)\\";
TO:
string PathFecha = string.Format("{0}{4}{1}{4}{2}{4}{3}{4}", ConfigurationManager.AppSettings.ToString(), Drp_List1.SelectedText, Drp_List2.SelectedText, Drp_List3.SelectedText, "\\");
Use Drp_List1.SelectedItem.Text if you need Text of selected dropdown menu item.
Use Drp_List1.SelectedItem.Value if you need Value of selected dropdown menu.
Do this for all dropdowns.
string PathFecha =
System.IO.Path.Combine(
ConfigurationManager.AppSettings.ToString(),
Drp_List1.SelectedItem.Text,
Drp_List2.SelectedItem.Text,
Drp_List3.SelectedItem.Text);
Using Path.Combine() may make it a little easier dealing with the paths.
Well it looks to me that with this line:
string PathFecha = ConfigurationManager.AppSettings.ToString() + "\\Convert.ToString(Drp_List1.SelectedItem)\\Convert.ToString(Drp_List2.SelectedItem)\\Convert.ToString(Drp_List3.SelectedItem)\\";
you are simply concatenating a single string to the base path, which is not what you want. Putting C# code into a string won't replace the result of that code in the string. What you want to do is concatenate each part of the path individually:
string PathFecha = Convert.ToString(Drp_List1.SelectedItem) + "\\"
+ Convert.ToString(Drp_List2.SelectedItem) + "\\"
+ Convert.ToString(Drp_List3.SelectedItem) + "\\";
And, as Gloria said, if you want to use the text of the selected item, you should use Drp_List1.SelectedItem.Text. So it should actually be:
string PathFecha = Drp_List1.SelectedItem.Text + "\\"
+ Drp_List2.SelectedItem.Text + "\\"
+ Drp_List3.SelectedItem.Text + "\\";

How to get only directory name from SaveFileDialog.FileName

What would be the easiest way to separate the directory name from the file name when dealing with SaveFileDialog.FileName in C#?
Use:
System.IO.Path.GetDirectoryName(saveDialog.FileName)
(and the corresponding System.IO.Path.GetFileName). The Path class is really rather useful.
You could construct a FileInfo object. It has a Name, FullName, and DirectoryName property.
var file = new FileInfo(saveFileDialog.FileName);
Console.WriteLine("File is: " + file.Name);
Console.WriteLine("Directory is: " + file.DirectoryName);
The Path object in System.IO parses it pretty nicely.
Since the forward slash is not allowed in the filename, one simple way is to divide the SaveFileDialog.Filename using String.LastIndexOf; for example:
string filename = dialog.Filename;
string path = filename.Substring(0, filename.LastIndexOf("\"));
string file = filename.Substring(filename.LastIndexOf("\") + 1);

Categories