I am trying to create a folder with a variable that can change, I am using
System.IO.Directory.CreateDirectory
When I hardcode a value like so:
var folder = #"C:\Users\Laptop\Documents\bot\random string here"
It creates that directory, but when I pass data to my method and try and use it like so:
var folder = #"C:\Users\Laptop\Documents\bot\" +
articlename.Replace(" ", "_");
System.IO.Directory.CreateDirectory(folder);
It doesn't create it nor break. How can I use the variable to create a folder like that?
My article is a random string like "hello this is a article yadda"
I solved by adding my paths together correctly as below
string path = root +"/"+ newfolder;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
// To move a file or folder to a new location:
//System.IO.File.Move(fi.FullName, path);
}
Related
I'm using a Script Task (C#) within SSIS to move all .txt files from one folder to another. However, when I execute this, nothing happens. The Script Task actually reports success but the text files do not move. I'm using variables for all the paths - they all start with 2 backslashes and end with 1 back slash.
All I want to do is move all text files from the source destination to the destination folder.
What am I missing?
public void Main()
{
DirectoryInfo di = new DirectoryInfo(Dts.Variables["IN_Folder"].Value.ToString());
string destinationFolder = Dts.Variables["User::IN_Folder_Processing"].Value.ToString();
string sourceFolder = Dts.Variables["User::IN_Folder"].Value.ToString();
FileInfo[] fi = di.GetFiles("*.txt");
String filename = fi[0].Name;
string sourceFileName = filename;
string destinationFile = destinationFolder + sourceFileName;
string sourceFile =sourceFolder + sourceFileName;
if (File.Exists(destinationFile))
File.Delete(destinationFile);
// To move a file or folder to a new location:
System.IO.File.Move(sourceFile, destinationFile);
Dts.TaskResult = (int)ScriptResults.Success;
}
Like I mentioned in the comments, there seems to be no need to use a Script Task to do this; a far better option would be a Foreach Loop Container and a FileSystem Task.
Firstly create the Foreach Loop Container, open the editor and go to the Collection Pane. Change Enumerator to Foreach File Enumerator. I assume you are using a variable for the directory, so click ... for Expressions and select Directory for the Property and your variable for the expression.
As you specifically want to deal with txt files, change Files to *.txt. What option you use for Retreive File Name depends on how your determining the destination. I'm going to assume you have another variable with the directory target, so select Name and extention.
Go to the Variable Mappings pane and select your filename variable, or create a new one. Leave the Index as 0. This will store the Name and extension of the file you are going to move.
Create a new variable in your package, called OriginalFilePath, or something easily identifiable. Set the value to string and then change the Scope to your Foreach Loop Container. Now open the expression pane for the variable and set the expression to something like:
#[User::SourceDirectoryVariable] + "\\" + #[User::FileNameVariable]
Obviously change the variable names to what they need to be. Now create a second variable (same settings), however, using your destination directory variable instead of the source (#[User::DestinationDirectoryVariable] + "\\" + #[User::FileNameVariable]).
Now, in your Control Flow, create a File System Task within your Foreach Loop Container. Change Operation to Move File. Then fill in the rest of the pane as needed (IsSourceVariable will be True, and then select your variable). Do the same for the destination, and then you should be good to go.
Any problems, please do comment with the error.
You should avoid manually concatenating file paths using the string + operator. This leaves a lot of room for error. Use System.IO.Path.Combine(). This ensures all leading and trialing slashes are formatted properly.
There's also no need to rebuild the file paths manually using all those additional variables. Something like this will work just fine so long as your input variable directories are correct:
public void Main()
{
DirectoryInfo di = new DirectoryInfo(Dts.Variables["IN_Folder"].Value.ToString());
string destinationFolder = Dts.Variables["User::IN_Folder_Processing"].Value.ToString();
FileInfo[] fi = di.GetFiles("*.txt");
foreach (FileInfo f in fi)
{
FileInfo destinationFile = new FileInfo(Path.Combine(destinationFolder, f.Name));
if (destinationFile.Exists)
destinationFile.Delete();
f.MoveTo(destinationFile.FullName);
}
Dts.TaskResult = (int)ScriptResults.Success;
}
I have to create multiple folders as e.g.
Directory.CreateDirectory("PATH\\" + _year + "filetosave.txt");
while "PATH\\" is the full path where the folder will reside, _year is the parameter and "filetosave.txt" is the file which is to be saved in respective folder.
And at run time, it should create respective folders with years in the folder name containing respective files to save.
Whereas .CreateDirectory() method only accepts string path or string path, security access as parameters.
How will we create these parameterized folders?
How can we make a check that a specified directory already exists or not?
var path = Path.Combine("PATH\\", _year.ToString(), "filettosave.txt");
Directory.CreateDirectory(path);
Directory.CreateDirectory
Creates all directories and subdirectories in the specified path unless they already exist.
Emphasis mine.
As commented, use Path.Combine when trying to build system paths:
var root = "Path";
var year = "2016";
var filename = "filetosave.txt";
var path = Path.Combine(root, year, filename);
// path = Path\2016\filetosave.txt
Directory.CreateDirectory(path);
In general, use System.IO.Path.Combine to build paths. It simplifies this task.
string dir = System.IO.Path.Combine(rootPath, _year.ToString());
Directory.CreateDirectory(dir);
string file = System.IO.Path.Combine(dir, "filetosave.txt");
FileStream fs = File.Create(file)
It sounds simple but it is not. I am trying to move a file that i made it like this:
string newFileName = string.Format("{0}-{1}-{2}-t{3:00}-{4:00}.txt", 2013, 10, 5, 05, 06);
It is going to look like: 2013-10-5-05-06.txt, from the default directory (..\bin\debug\2013-10-5-05-06.txt) to another directory (c:\Users\Public\Folder). I want to keep the name of the file so that other files having almost the same name (small difference between) being moved to the same folder. I tried several methods (Path.Combine(), string.Concat()..) without success.
Just use this snippet
string CurrentFileNameAndPath; //the path the file you want to move
string newPath; //only the new the folderPath
System.IO.FileInfo FileYouWantToMove = new System.IO.FileInfo(CurrentFileNameAndPath);
string NewFileNameAndPath = newPath + "\\" + FileYouWantToMove.Name; //remember that using fullname will get the folder and filename
FileYouWantToMove.MoveTo(NewFileNameAndPath);
So lets use this as an example i have this file C:/Dir1/file1.txt and I want to change its directory to C:/Dir2/ right? then it will be like this
string CurrentFileNameAndPath = #"C:/Dir1/file1.txt";
string newPath = #"C:/Dir2/";
System.IO.FileInfo FileYouWantToMove = new System.IO.FileInfo(CurrentFileNameAndPath);
string NewFileNameAndPath = newPath + "\\" + FileYouWantToMove.Name;
FileYouWantToMove.MoveTo(NewFileNameAndPath);
the result will the that file in C:/Dir1/file1.txt will be now in C:/Dir2/file1.txt it have been moved and maintened the same file name and extension
Something like this is actually pretty trivial
var srcFile = "..\bin\debug\2013-10-5-05-06.txt";
var destFolder = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
var destFile = Path.Combine(destFolder, Path.GetFileName(srcFile));
File.Move(srcFile, destFile);
Just keep in mind that Move can throw various exceptions e.g. IOException / UnauthorizedAccessException etc. so it would be wise to handle these where appropriate.
In the below code, the files are being saved in the debug folder of the project, I want to store the files in the appdata folder under a generic specified folder!
AViewModel vm = DataContext as AViewModel;
var table = vm.FileSelectedItem;
if (table != null)
{
var filename = System.IO.Path.GetTempFileName();
File.WriteAllBytes(table.FileTitle, table.Data);
Process prc = new Process();
prc.StartInfo.FileName = table.FileTitle;
prc.Start();
}
//table.FileTitle is the name of the file stored in the db
// eg:(test1.docx, test2.pdf, test3.txt, test4.xlsx)
//table.Data is public byte[] Data { get; set; } property
// which stores the files coming from the db.
I am looking at GetFolderPath and trying something like this now
System.IO.Path.GetTempFileName(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
Thanks for any replys!
GetTempFileName returns a full path to a file in the user's temp path. You can't use that to create a file within a specific folder.
Given that you want to store within the AppData folder already, perhaps you are after something more like:
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "YourCompany\\YourProduct\\Output");
var filename = Path.Combine(path, table.FileTitle);
File.WriteAllBytes(filename, table.Data);
Process.Start(filename);
In case you want to create randomly named file under AppData, you can try
Guid.NewGuid().ToString("N")
That'll give you random string with reasonable certainty it is unique. For folder under AppData:
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Guid.NewGuid().ToString("N"));
Note: at least put it into some subfolder, AppData is folder shared with all other apps.
how can i assign a to a variable, which is located at the same project, for example at my project i created a folder named App_Data and for example the file is file.dat , how can i assign the file at a variable,.. for example:
var file = App_Data/file.dat
I need it to be assigned to a variable because i will be using that variable as a parameter to a method,.. it used to be :
var file= HttpContext.Current.Request.MapPath("/App_Data/file.dat");
but now i want the path to be at the same project
if it should be absolute path it should be fine too
The MapPath should give you the absolute location of the file on disk from a relative url to the root of your website:
var absoluteFileLocation = HostingEnvironment.MapPath("~/App_Data/file.dat");
This should return something like:
c:\inetpub\wwwroot\MyWebSite\App_Data\file.dat
UPDATE:
It looks like you are trying to retrieve the contents of the file, not the location. Here's how this could be done:
var absoluteFileLocation = HostingEnvironment.MapPath("~/App_Data/file.dat");
string fileContents = System.IO.File.ReadAllText(absoluteFileLocation);
You need to read the file using one of the available methods (Streams, Readers, etc).
The easiest would be:
string fileContent = File.ReadAllText(fileNameAndPath);
where the variable fileNameAndPath contains the full path and file name to the file as described by Darin Dimitrov.
Your intention isn't exactly clear, anyway:
if you want file stats:
System.IO.File file = new System.IO.File("~/App_Data/file.dat");
if you want the file content use:
public static string readFileContent(String filename)
{
try
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(filename))
return sr.ReadToEnd();
}
catch { return String.Empty; }
}