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)
Related
in this I am trying to load all the excel data from specified folderpath and its subfolder present inside it to sql server... Problem is I am able to read the main folder and subfolder, but while taking the data from sub folder file it taking the path of main folder for that sub folder file
example: file path - d:\test
sub directory : d:\test\test2
inside subdirectory my file is present but when iterating it is reading the path of sub directory file as : d:\test\file_name
please help in this
```DirectoryInfo directory = new DirectoryInfo(#FolderPath);
FileInfo[] files = directory.GetFiles("*.xlsx", SearchOption.AllDirectories);```
// Directory structure:
// C:\Temp\ExcelFiles\Excel1.xlsx
// C:\Temp\ExcelFiles\SubFolder\Excel2.xlsx
var path = #"C:\Temp\ExcelFiles";
var allExcelFilesInPathAndSubFolders = Directory.GetFiles(path, "*.xlsx", SearchOption.AllDirectories);
This approach returns the expected 2 Excel file names as string array (i.e. C:\Temp\ExcelFiles\Excel1.xlsx and C:\Temp\ExcelFiles\SubFolder\Excel2.xlsx).
The approach in your post returns an array of FileInfo. You can get all relevant information from that; the name with or without path, the file extension, and using Path.GetFileNameWithoutExtension you can get the name without extension.
// Directory structure:
// C:\Temp\ExcelFiles\Excel1.xlsx
// C:\Temp\ExcelFiles\SubFolder\Excel2.xlsx
var path = #"C:\Temp\ExcelFiles";
DirectoryInfo directory = new DirectoryInfo(path);
FileInfo[] files = directory.GetFiles("*.xlsx", SearchOption.AllDirectories);
// Excel1.xlsx
var firstFileName = files.First().Name;
// Excel1
var firstFileNameWithoutExtension = Path.GetFileNameWithoutExtension(files.First().Name);
// .xlsx
var fileFileExtension = files.First().Extension;
// C:\Temp\ExcelFiles\Excel1.xlsx
var firstFileFullName = files.First().FullName;
I'm trying to get a latest file from a path and copying it, then paste it into a generated folder.
This is what I tried so far:
// This Method is called if the function/method CopyContent is invoked by the user or a bound event.
// Return true, if this component has to be revalidated!
public bool OnCopyContent(int arg)
{
// Get latet file from the specificed Folder
var directory = new DirectoryInfo(#""+sourceFolderPath);
var myFile = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();
// Newly Created Folder Name
string generatedFolderName = destinationFolderName;
// Newly Creted Folder Path (i.e C://Users/Desktop) Cretge it on desktop with name "Paste me here "
string generatedPathString = System.IO.Path.Combine(destinationFolderPath, generatedFolderName);
if (!File.Exists(generatedPathString))
System.IO.Directory.CreateDirectory(generatedPathString);
// Copy the Latet file to the newly Created Folder on the Desktop
string destFile = Path.Combine(#""+destinationFolderPath, myFile.Name);
File.Copy(myFile.FullName, destFile, true);
return false;
}
What im trying to do is
1 : I have Specifed Folder Path , i want to copy it's latest file in it depending on timee
2: Create new Folder on Desktop with name " NewlyAdded"
3: Paste the Copied File from the Specifed Folder to the Newly Created Folder
now my issue is how to copy it
simply : take the file name ans pass it with the destination folder to a string,
then pass the file.FullName to Copy() method and it'll be copied.
This code tested and worked.
EDIT : Added a line to generate folder if not exist, and copy the file to it.
string newFolder = "NewlyAdded";
string path = System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
newFolder
);
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
var directory = new DirectoryInfo(#"Sourcd folder");
var myFile = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();
string destFile = Path.Combine(path, myFile.Name);
System.IO.File.Copy(myFile.FullName, destFile, true);
the true as a last parameter is to overwrite if exist.
Looking at the documentation, the first parameter is the path of the original file...
https://msdn.microsoft.com/en-us/library/9706cfs5(v=vs.110).aspx
I have trying to copy it however im not sure now how to pass it in
You use the file path of the original, not the FileInfo itself!
Like this:
var directory = new DirectoryInfo(#"C:\");
FileInfo myFile = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();
string filePath = myFile.FullName;
You'd use this filePath variable, not the FileInfo instance you're currently using.
if you coudn't copy string file then open your current file which you want to copy in binary read (rb) and store that in variable.
after write that file in particular directory by using binary write
may be it should help you
In my project there is a folder and in that folder there is text file. I want to read that text file
string FORM_Path = #"C:\Users\...\Desktop\FormData\Login.txt";
bool first = true;
string line;
try
{
using (StreamReader streamReader = File.OpenText(FORM_Path))
{
line = streamReader.ReadLine();
}
}
but I always get an error - file does not exist. how can i solve the problem in the path of text file.
Make sure your file's properties are set to copy the file to output directory. Then you can use the following line to get full path of your text file:
string FilePath = System.IO.Path.Combine(Application.StartupPath, "FormData\Login.txt");
You path is not in correct format. Use #".\FormData\Login.txt" instead of what you have
You are trying to give relative path instead of physical path. If you can use asp.net use Server.MapPath
string FORM_Path = Server.MapPath("~/FormData/Login.txt");
If the text file is in execution folder then you can use AppDomain.BaseDirectory
string FORM_Path = AppDomain.CurrentDomain.BaseDirectory + "FormData\\Login.txt";
If it is not possible to use some base path then you can give complete path.
Avoid using relative paths. Instead consider using the methods in the Path class.
Path.Combine
Path.GetDirectoryName
Step 1: get absolute path of the executable
var path = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
Step 2: get the working dir
var dir = Path.GetDirectoryName(path);
Step 3: build the new path
var filePath = Path.Combine(dir , #"FormData\Login.txt");
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.
If
frompath = "c:\\progfiles\\mobileapp\\es-gl\\a.dll"
and
topath = "c:\\progfiles\\mobileapp\\es-gl\\a.dll"
I want to copy file from frompath to topath.
If topath does not exist, then the directories and sub directories must get created and the file a.dll must copy from frompath to topath. I am using c# .net Compact Framework.
I think you are after the System.IO namespace. Using File.Copy can provide the solution.
And Directory.Exists / create can make the directory is not existing.
var fileName = "tmp.txt";
var from = #"c:\temp\" + fileName;
var to = #"c:\temp\1\";
if (!Directory.Exists(to))
Directory.CreateDirectory(to);
File.Copy(from, to + fileName);
You can go for FileInfo aswell. (Also in the System.IO namespace)
var file = new FileInfo(#"c:\temp\tmp.txt");
var to = #"c:\temp\1\";
if (!Directory.Exists(to))
Directory.CreateDirectory(to);
file.CopyTo(to + file.Name);