I wanted to exclude a folder within directory when copying the directory to other location could anyone please help me out ?
string logZipTarget = "PangaeaLogs_Fail_" + currentLocation + "_" + classID + "_" + tracer + "_" +
DateTime.Now.ToString("ddMMMyyyy-HH-mm-ss", System.Globalization.CultureInfo.InvariantCulture) + ".zip";
string buildTypeFile = #"C:\build.typ";
string journalFile = #"C:\Mavis\" + tracer + ".ejl";
string logsPath = #"C:\Pangaea\PangaeaFinancialLogs\"; //Path to copy directory to
File.Copy(buildTypeFile, logsPath + "build.typ", true);
File.Copy(journalFile, logsPath + tracer + ".ejl", true);
Helper.DirectoryCopy(#"C:\Program Files\NCR\Pangaea\", logsPath, true);
executor.ZipFolder(logsPath, logZipTarget);
Inside this location C:\Pangaea\PangaeaFinancialLogs\ApplicationData i wanted to remove this folder SessionBackup but what is happening is it is copyin all the folders inside this location
string logsPath = #"C:\Pangaea\PangaeaFinancialLogs\";
From the bit of code provided in your comment I can only assume which classes your using. If I'm correct this should do the trick:
DirectoryInfo currentFolder = new DirectoryInfo("");
String NameOfFolderNotToInclude = "";
if(currentFolder.Name != NameOfFolderNotToInclude)
{
File.Copy(newPath, newPath.Replace(#"\\xxx\yyy", #"C:\bbb"), true);
}
Always keep in mind that equals (MSDN) if not overidden will always compare the actual objects for equality. In your case a string will never be the same as a DirectoryInfo and thus not be equal even if the DirectoryInfo is pointing at the location the string describes.
Related
I need to write a code in script component in SSIS that will move files to corresponding folders. Files that I'm getting are usually named, for example "Dem323_04265.45.23.4", "Dem65_459.452.56", "Ec2345_456.156.7894" and I need to move them to a corresponding folders. The name of my folders are "Oklahoma City (323)", "New York(65)".. I need to move those files to matching folders, so for example "Dem323_04265.45.23.4" would go to folder "Oklahoma City (323)". I need to modify my code so the number that is located between first two or three letter and underline matches number located in parenthesis. I've been working on this for several days already and I'm new with ssis and c#, so any help would be appreciated. This is the code I have so far:
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);
var folderNumber = Regex.Match(
filename,
//Dts.Variables["OutputMainFolder"].Value.ToString(),
#"\(([^)]*)\)").Groups[1].Value;
FolderExistFlg = Directory.Exists(Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + folderNumber);
if (!FolderExistFlg)
{
Directory.CreateDirectory(Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + folderNumber);
}
File.Move(Dts.Variables["SourceFolder"].Value.ToString() + "\\" + filename + "\\" + folderNumber,
Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + 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
}
}
Here you go, the below snippet would move the files as per the match criteria. You need to take care of the source input as per your configuration.
string filePath = #"C:\Packages\StackOverflow";
//string fileName = string.Empty;
//get list of files
string[] filePaths = Directory.GetFiles(filePath);
//get list of folders
string[] dirPaths = Directory.GetDirectories(filePath);
//loop through the files and move them
foreach(string fileNames in filePaths)
{
string[] pathArr = fileNames.Split('\\');
string fileName = pathArr.Last().ToString();
int index = fileName.IndexOf('_');
string fileNamePart = fileName.Substring(0, index);
//get the first numeric part of the filename to perform the match
var fileNameNumPart = Regex.Replace(fileNamePart, "[^0-9]", "");
//find related directory
var dirMatch = dirPaths.FirstOrDefault(stringToCheck => stringToCheck.Contains(fileNameNumPart.ToString()));
if (dirMatch != null)
{
// move would fail if file already exists in destination
if (!File.Exists(dirMatch + '\\' + fileName))
{
File.Move(fileNames, dirMatch + '\\' + fileName);
}
}
}
I am trying to build a method which is able to write in a file the number of files in another folder. I already got it but it does not work because gives me an error:
Could not find a part of the path '
C:\Users\Administrator\Desktop...\bin\release\%USERPROFILE%\AppData\Local_logC'
This is my code:
private static int GetCountGFiles(string dirname)
{
int fileCount = 0;
dirname = dirname.TrimEnd(new char[] { '\\' }) + #"\";
var fixedDirname = Environment.ExpandEnvironmentVariables(dirname);
fileCount += System.IO.Directory.GetFiles(fixedDirname).Length;
string[] all_subdirs = System.IO.Directory.GetDirectories(dirname);
foreach (string dir in all_subdirs)
fileCount += GetCountGFiles(dirname);
string data = string.Format("LogReg.txt");
System.IO.Directory.CreateDirectory(filePath);
var fileandpath = filePath + data;
using (StreamWriter writer = File.AppendText(fileandpath))
{
writer.WriteLine("[" + DateTime.Now + "]" + " - " + "NÂș de Records: (" + fileCount.ToString() + ")");
}
return fileCount;
}
And then I call the method like this :
GetCountGFiles(#"%USERPROFILE%\AppData\Local\Cargas - Amostras\_logsC\");
What should I do?
Methods like Directory.GetFiles and Directory.GetDirectories will not automatically figure out what the environment variables that you pass to it are. You need to do that manually with Environment.ExpandEnvironmentVariables. For example:
var fixedDirname = Environment.ExpandEnvironmentVariables(dirname);
Now you can do this:
fileCount += System.IO.Directory.GetFiles(fixedDirname).Length;
(PS No need to use ToString() on a string)
That "%USERPROFILE%" part is a placeholder for an environment variable. The file APIs have no idea how to handle that.
You need to use Environment.ExpandEnvironmentVariables on your input string,
before passing it to Directory.GetFiles
I am currently working on a project that sweeps a mailbox for attachments and when one is found it is placed in the user's directory. My problem is that when I check if the file exist in the path, I alter the attachment's name and add a counter and time stamp, that way it is not over written. However, when it goes into the condition and changes the file name it never updates the path variable to include the right value of the Clean name variable.
string timeProcessed = DateTime.Now.ToString();
byte[] bytefiles = attachment.ContentBytes;
string cleanName = MakeCleanName(userEmail.Subject, attachment.Name);
string path = employeeStarPath + "\\" + cleanName;
// updated this in order to prevent images with the same name from overwritting eachother.
if (File.Exists(path))
{
cleanName = Path.GetFileNameWithoutExtension(attachment.Name).ToString()+"(" + counter + ")" + "-(Recieved - " + timeProcessed.Replace(":",".").Replace("/",".") + " )"+ Path.GetExtension(attachment.Name); << this value is not updated in the path variable.
}
Now I am aware I can update the path var by calling path = employeeStarPath + "\\" + cleanName; again but I feel that this makes my code a bit confusing.
I might not understood your question but can you just call the line "string path = employeeStarPath + "\" + cleanName;" at the end instead before the if?
string timeProcessed = DateTime.Now.ToString();
byte[] bytefiles = attachment.ContentBytes;
string cleanName = MakeCleanName(userEmail.Subject, attachment.Name);
// updated this in order to prevent images with the same name from overwritting eachother.
if (File.Exists(path))
{
cleanName = Path.GetFileNameWithoutExtension(attachment.Name).ToString()+"(" + counter + ")" + "-(Recieved - " + timeProcessed.Replace(":",".").Replace("/",".") + " )"+ Path.GetExtension(attachment.Name); << this value is not updated in the path variable.
}
string path = employeeStarPath + "\\" + cleanName;
After the else block Path.Combine method combines every part and gives the file name when Console.WriteLine(result); is used. But it doesn't actually create the file with that name.
I want to get the EmployeeDetails.txt file, make a version of it (i.e. renaming the filename) and saves it to C:\Hitory folder.
How to achieve that?
Using File.Move throws FileNotFoundexception
void ModRec()
{
string filename = #"C:\Current\EmployeeDetails.txt";
string current = #"C:\Current\";
string history = #"C:\History\";
FileInfo fileinfo = new FileInfo(filename);
if (fileinfo.Exists)
{
if (!Directory.Exists(history))
{
Directory.CreateDirectory(history);
}
}
else
{
Console.WriteLine("\t\t\tFile doesn't exist!");
Console.ReadLine();
Menu1();
}
var extension = Path.GetExtension(filename);
var fileNamePart = Path.GetFileNameWithoutExtension(filename);
var path = Path.GetDirectoryName(filename);
var version = 0;
string result;
do
{
version++;
result = Path.Combine(path, fileNamePart + "_" + version + extension);
}
while (File.Exists(result));
//File.Move(current, history);
}
Your loop at the end needs to change slightly, because
result = Path.Combine(path, fileNamePart + "_" + version + extension);
is looking in the directory where the file already is, rather than in the history directory where you want it to be, so you'll be scanning for duplicates in the wrong location. The Path.Combine therefore needs to reference the value of history:
result = Path.Combine(history, fileNamePart + "_" + version + extension);
Secondly, you cannot use Move to move a file to a directory in the same way that you can from the command line, you need to specify the two parameters as filenames, so
File.Move(current, history);
becomes
File.Move(filename, result);
The resulting code at the end of your method should therefore look like this:
do
{
version++;
result = Path.Combine(history, fileNamePart + "_" + version + extension);
}
while (File.Exists(result));
File.Move(filename, result);
Incidentally, where you test whether the file already exists, you simply call Menu1 and then carry on. Can you guarantee that that will ensure that the next thing that the user does will create a valid file? I'm guessing that it most likely cannot guarantee that, so you should exit your method at that point, or perhaps put the remainder of the body inside the fileinfo.Exists block.
That leaves the desirability of invoking a menu from inside this method, but that's a design question outside of the scope of what you've asked here.
Try this instead:
void ModRec()
{
string filename = #"C:\Current\EmployeeDetails.txt";
string current = #"C:\Current\";
string history = #"C:\History\";
FileInfo fileinfo = new FileInfo(filename);
if (fileinfo.Exists)
{
if (!Directory.Exists(history))
{
Directory.CreateDirectory(history);
}
}
else
{
Console.WriteLine("\t\t\tFile doesn't exist!");
Console.ReadLine();
Menu1();
}
var extension = Path.GetExtension(filename);
var fileNamePart = Path.GetFileNameWithoutExtension(filename);
var path = Path.GetDirectoryName(filename);
var version = 0;
string result;
do
{
version++;
result = Path.Combine(history, fileNamePart + "_" + version + extension);
}
while (File.Exists(result));
File.Move(filename, result);
}
Path.Combine() does not touch filesystem at all. No files/folders would be ever crated.
Try File.Move(filename, history);. That is, instead of current, which is a directory, move the file (assuming filename is a full path).
I am trying to download images. Their link may be image.png or http://www.example.com/image.png.
I made the image.png be added to the host and passed it to a list. So image.png is now http://www.example.com/image.png
But if the other type is used what I get is http://www.example.com//http://www.example.com/image.png
All I need is to get the string after the third slash. Here is some code I am tried to use:
try
{
path = this.txtOutput.Text + #"\" + str4 + etc;
client.DownloadFile(str, path);
}
catch(Exception e)
{
var uri = new Uri(str);
String host = (String) uri.Host;
String pathToFile = "http://" + host + "/";
int len = pathToFile.Length;
String fin = str.Substring(len, str.Length - len);
path = this.txtOutput.Text + #"\" + str4 + etc;
client.DownloadFile(fin, path);
}
What are these variables all about, like str4, etc and so on? Instead of the try catch you could check wheter the string is a valid uri. Give a look here. Try to debug you code line on line and check every single variable, then you will see which line makes the mistake.
EDIT
If I understodd you right, then this would be your solution:
string wrongResult = "example.com//http://www.example.com/image.png";
string shouldResult = "example.com/image.png";
int listIndexOfHttp = wrongResult.LastIndexOf("http:");
string correctResult = wrongResult.Substring(listIndexOfHttp);
When not please describe more specific from where you get this and it is always the same structure? or alaways different?