I'm using SSIS and a script task in C#.
I have a FOR EACH Loop that looks into a folder and assigns the full path and file name of each file found to a variable called FileNameFound which in turn is then assigned to a variable called filepath within the Script Task.
I also have a Project parameter that stores an output path, this is being assigned to 'newFilepath' within the Script Task.
Using some other code I then Encrypt the csv file.
Bottom line is, I need the output to go into a different folder then where it was found but retain the same filename.
e.g.
find a file: c:\folder\test.csv
encrypt and output to c:\folder\new folder\test.csv
I need newFilepath to be the variable $Project::CSV_OutputFolder + test.csv
I am trying to incorporate GetFileNameWithoutExtension(String) but keep receiving the error:
The name 'GetFileNameWithoutExtension' does not exist in the current context
This is my code:
public void Main()
{
// Get the filepath of the file that needs to be encrypted.
string filepath = Dts.Variables["FileNameFound"].Value.ToString();
// build output path
string newFilepath = Dts.Variables["$Package::$Project::CSV_OutputFolder"].Value.ToString() + GetFileNameWithoutExtension(Dts.Variables["FileNameFound"].Value.ToString())+ ".csv";
// Get password from SSIS variable
string encryptionKey = Dts.Variables["EncryptionKey"].ToString();
// Create an encrypted copy of the file
Encrypt(filepath, newFilepath, encryptionKey);
// Close Script Task
Dts.TaskResult = (int)ScriptResults.Success;
}
What am I missing?
I got it working. I change the For Each to just retrieve the filename only then amended my code:
public void Main()
{
// Get the filepath of the file that needs to be encrypted.
string filepath = Dts.Variables["Unencrypted_Folder"].Value.ToString() + Dts.Variables["FileNameFound"].Value.ToString();
// build output path
string newFilepath = Dts.Variables["$Project::CSV_OutputFolder"].Value.ToString() + Dts.Variables["FileNameFound"].Value.ToString();
// Get password from SSIS variable
string encryptionKey = Dts.Variables["EncryptionKey"].ToString();
// Create an encrypted copy of the file
Encrypt(filepath, newFilepath, encryptionKey);
// Close Script Task
Dts.TaskResult = (int)ScriptResults.Success;
}
Path.GetFileNameWithoutExtension(Dts.Variables["FileNameFound"].Value.ToString())
as it is static class in System.IO namespace.
Related
Hi I have a code that you can save file and give specific file naming.
the problem is how can I check if file exist in the folder directory.
What I'm trying to do is like this.
FileInfo fileInfo = new FileInfo(oldPath);
if (fileInfo.Exists)
{
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
fileInfo.MoveTo(string.Format("{0}{1}{2}", newPath, extBox1t.Text + "_" + textBox2.Text + "_" + textBox3.Text, fileInfo.Extension));
im trying to add MessageBox.Show in the below
if (!Directory.Exists(newPath))
{
MessageBox.Show("File Exist. Please Rename!");
Directory.CreateDirectory(newPath);
But it does not work. Or is there a way to add extension name at the last part of filename it should like this
Example: STACKOVERFLOWDOTCOME_IDNUM_11162022_0
if STACKOVERFLOWDOTCOME_IDNUM_11162022 exist it will rename to STACKOVERFLOWDOTCOME_IDNUM_11162022_0
it will add _0 at the last part.
One way to do it is to write a method that extracts the directory path, name, and extension of the file from a string that represents the full file path. Then we can create another variable to act as the "counter", which we'll use to add the number at the end of the file name (before the extension). We can then create a loop that checks if the file exists, and if it doesn't we'll increment the counter, insert it into the name, and try again.
For example:
public static string GetUniqueFileName(string fileFullName)
{
var path = Path.GetDirectoryName(fileFullName);
var name = Path.GetFileNameWithoutExtension(fileFullName);
var ext = Path.GetExtension(fileFullName);
var counter = 0;
// Keep appending a new number to the end of the file name until it's unique
while(File.Exists(fileFullName))
{
// Since the file name exists, insert an underscore and number
// just before the file extension for the next iteration
fileFullName = Path.Combine(path, $"{name}_{counter++}{ext}");
}
return fileFullName;
}
To test it out, I created a file at c:\temp\temp.txt. After running the program with this file path, it came up with a new file name: c:\temp\temp_0.txt
I've created a backup and restore procedure for my application. When the backup is run, it will create a .zip file of the SQLite database in the same directory as the database.
When restoring the database, it will rename the database, changing it from EPOSDatabase.db3 to tempEPOS.db3
Then, it takes the selected file and extracts it to the same location, under the name EPOSDatabase.db3, before deleting the renamed temporary database.
string dbPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
if (File.Exists(dbPath + "/tempEPOS.db3"))
{
File.Delete(dbPath + "/tempEPOS.db3");
};
File.Move(dbPath + "/EPOSDatabase.db3", dbPath + "/tempEPOS.db3");
ZipFile.ExtractToDirectory(dbPath + "/" + fileToRestore, dbPath + "/EPOSDatabase.db3");
File.Delete(dbPath + "/tempEPOS.db3");
My issue is that when I then have code that opens the connection, for example when I open the system settings page after the restore has been carried out, I get an error:
"Could not open database file: /data/user/0/com.companyname.ACPlus_MobileEPOS/files/EPOSDatabase.db3 (CannotOpen)"
As a further debug test, I added this code to the startup of the application:
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
foreach (var file in Directory.GetFiles(path))
{
string strFile = Convert.ToString(file);
}
public readonly string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "EPOSDatabase.db3");
var db = new SQLiteConnection(dbPath);
db.CreateTable<Category>();
db.CreateTable<SystemSettings>();
db.Close();
In the foreach loop, it only found the original .zip file that I was trying to restore from.
Then when it reaches the line
var db = new SQLiteConnection(dbPath);
it fails to create the database with the message
"Could not open database file: /data/user/0/com.companyname.ACPlus_MobileEPOS/files/EPOSDatabase.db3"
It seems like the file doesn't exist, so hasn't extracted properly, but if that was the case then why does it not just create a new database, rather than try to open it?
The extraction logic needs to be rechecked.
Specifically ExtractToDirectory.
Extracts all the files in the specified zip archive to a directory on the file system.
public static void ExtractToDirectory (string sourceArchiveFileName, string destinationDirectoryName);
In the original code
ZipFile.ExtractToDirectory(dbPath + "/" + fileToRestore, dbPath + "/EPOSDatabase.db3");
The contents of the zip file are extracting to a directory called {path}/EPOSDatabase.db3/.
If the goal was just to extract from the archive to the directory then only the directory location is required.
ZipFile.ExtractToDirectory(dbPath + "/" + fileToRestore, dbPath);
Additionally, a check should be done to make sure the desired file actually exists after the restore before deleting the old file.
//... extraction code omitted for brevity
if (!File.Exists(dbPath + "/EPOSDatabase.db3")) {
//...either throw error or alert that database is not present
//...could consider return old file back to original sate (optional)
} else {
File.Delete(dbPath + "/tempEPOS.db3");
}
After going through all the related stuff to copying files i am unable to find an answer to my
problem of an exception occurring while i was trying to copy a file to an empty folder in WPF application. Here is the code snippet.
public static void Copy()
{
string _finalPath;
foreach (var name in files) // name is the filename extracted using GetFileName in a list of strings
{
_finalPath = filePath; //it is the destination folder path e.g,C:\Users\Neha\Pictures\11-03-2014
if(System.IO.Directory.Exists(_finalPath))
{
_finalPath = System.IO.Path.Combine(_finalPath,name);
System.IO.File.Copy(name, _finalPath , true);
}
}
}
While debugging exception is occuring at file.copy() statement which says
"FileNotFoundException was unhandled" could not find file
i already know about the combining path and other aspects of copy but i dont know why this exception is being raised.
I am a noob to WPF please help.........
Use following code:
public static void Copy()
{
string _finalPath;
var files = System.IO.Directory.GetFiles(#"C:\"); // Here replace C:\ with your directory path.
foreach (var file in files)
{
var filename = file.Substring(file.LastIndexOf("\\") + 1); // Get the filename from absolute path
_finalPath = filePath; //it is the destination folder path e.g,C:\Users\Neha\Pictures\11-03-2014
if (System.IO.Directory.Exists(_finalPath))
{
_finalPath = System.IO.Path.Combine(_finalPath, filename);
System.IO.File.Copy(file, _finalPath, true);
}
}
}
The GetFileName ()
only returns the actual name of the file (drops the path) what you want is a full path to the file. So you getting an exception because the 'name' does not exist on your drive (path is unknown)
You're variable, name, is most likely just the file name (i.e. something.jpg). When you use the File.Copy(...) method, if you do not supply an absolute path the method assumes a path relative to the executable.
Basically, if you are running your app in, for example, C:\Projects\SomeProject\bin\Debug\SomeProject.exe, then it is assuming your file is C:\Projects\SomeProject\bin\Debug\something.jpg.
I want to check to see if a file exists in a particular folder from SSIS. How can I accomplish this?
Variables:
folder - string - C::\Temp\
file - string - 1.txt
fileExists - boolean - False
public void Main()
{
string folder = Dts.Variables["User::folder"].Value.ToString(); //#"C:\temp\";
string file = Dts.Variables["User::file"].Value.ToString(); //"a.txt";
string fullPath = string.Format(#"{0}\{1}", folder, file);
Dts.Variables["User::fileExists"].Value = File.Exists(fullPath);
Dts.TaskResult = (int)ScriptResults.Success;
}
You can use Foreach Loop Container and simply place all your items into it. It will be executed if file exists and won't if not. Very simple :)
As an alternative to having an "out" variable, you could also Change the Dts.TaskResult based on whether or not the file exists. The snippet below fails the script task if the file doesn't exist. (It also creates a log entry if logging is enabled.)
public void Main()
{
string fileName = Dts.Variables["User::sourcePath"].Value.ToString() + Dts.Variables["User::fileName"].Value.ToString();
if (File.Exists(fileName))
{
Dts.TaskResult = (int)ScriptResults.Success;
}
else
{
Dts.Log(string.Format("File {0} was not found.",fileName),0,null);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
There are no native tasks inside SSIS that can do this check but you can accomplish this using a Script Task but i suggest you check the following links for simple steps required to achieve that.
http://www.bidn.com/blogs/DevinKnight/ssis/76/does-file-exist-check-in-ssis
http://sqlmag.com/sql-server-integration-services/simple-effective-way-tell-whether-file-exists-using-ssis-package
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);
}