I have a C# console application that sends Excel spreadsheet attachments through email.
I have given the file path in App.config. While trying to find the file, the code looks at proper location. But when trying to attach the file inside the foreach statement, it is looking in code's bin folder.
What am I doing wrong here?
DirectoryInfo dir1 = new DirectoryInfo(ConfigurationManager.AppSettings.Get("FilePath"));
FileInfo[] folderFiles = null;
folderFiles = dir1.GetFiles();
foreach (FileInfo aFile in folderFiles)
{
message.Attachments.Add(new Attachment(aFile.Name));
}
You need to use aFile.FullName (includes the full path) rather than aFile.Name (only the filename). If a command is not doing what you expect, you should check the documentation.
Alternatively, you could make it simpler:
string dir1 = ConfigurationManager.AppSettings.Get("FilePath");
foreach(string aFile in Directory.EnumerateFiles(dir1))
{
message.Attachments.Add(new Attachment(aFile));
}
as Directory.EnumerateFiles simply returns the full filenames and you would have to think about not doing so (e.g. by using Path.GetFileName) to do otherwise.
Related
I have a web directory that contains files and I want to delete them all. I've looked online but all the answers rely on the file system and I want to use the website's directories. I tried this:
foreach (string file in HttpContext.Current.Server.MapPath("\\MyDirectory"))
{
File.Delete(file);
}
The foreach statement is underlined and the error is 'cannot convert type char to string'.
What's the syntax to delete all files in a directory?
Your might need to correct your MapPath parameter (\\MyDirectory), but the syntax you need is shown below.
System.IO.DirectoryInfo di= new DirectoryInfo(HttpContext.Current.Server.MapPath("\\MyDirectory"));
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
Server.MapPath gives you a directory path, not an array of files/folders. IF you want to remove all files in the folder you would do this:
var folderPath = HttpContext.Current.Server.MapPath("\\MyDirectory");
foreach (string file in Directory.GetFiles(folderPath))
{
File.Delete(file);
}
If you wanted do delete the folder, then
var folderPath = HttpContext.Current.Server.MapPath("\\MyDirectory");
Directory.Delete(folderPath);
To delete all folders within the main folder
var folderPath = HttpContext.Current.Server.MapPath("\\MyDirectory");
foreach (string file in Directory.GetDirectoriesfolderPath))
{
File.Delete(file);
}
So I'm writing some code that is going through a directory of .xlsx files and picking the file that was created last. It's a simple task, but there is something a bit strange happening with the Name property of a particular FileInfo object and potentially there are more cases of this occurring.
Here is my code:
DirectoryInfo di = new DirectoryInfo(FolderPath);
FileInfo[] FileArray = di.GetFiles("*.xlsx", SearchOption.AllDirectories);
if (FileArray.Count() != 0)
{
DateTime latestDate = DateTime.MinValue;
string FileName = String.Empty;
foreach (FileInfo File in FileArray)
{
if (File.CreationTime > latestDate)
{
latestDate = File.CreationTime;
FileName = File.FullName;
}
}
}
The FileName is important because I use it to query the latest file for information and display it. However, the Name property of a particular .xlsx file (potentially more) is appearing like this ~$File.xlsx when in fact the file name is really File.xlsx. This causes the FullName property to contain these characters as well.
Is there any way to fix this? What triggers this?
Opening an xlsx file results in Excel creating a hidden file with the same name preceded by "~$". So if one of these Excel files are open at the time you retrieve the content of the directory, you will also get the temp file.
Add a filter that excludes hidden files and your issue is fixed.
Example:
FileAttributes attributes = File.GetAttributes(path);
if((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
{
// Hidden file, just skip it
}
From http://msdn.microsoft.com/en-us/library/system.io.file.getattributes.aspx
~$ indicates that the file is a temporary file used by Microsoft Office. See here for additional information.
I have a folder - "C:\scripts"
Within "scripts" I have several sub folders e.g. - "C:\scripts\subfolder1" "C:\scripts\subfolder2" etc, that contain html files.
I am trying to use the following code -
foreach (string file in Directory.EnumerateFiles(#"C:\scripts","*.html"))
{
string contents = File.ReadAllText(file);
}
However this does not work due to the html files being in the sub folders.
How can I access the html files in the sub folders without having to manually put in the path of each sub folder?
use this overload from DirectoryInfo
var dir = new DirectoryInfo(#"c:\scripts");
foreach(var file in dir.EnumerateFiles("*.html",SearchOption.AllDirectories))
{
}
Directory.EnumerateFiles(#"C:\scripts","*.html",SearchOption.AllDirectories)
Seems to be the right solution for me try it :)
Maybe this works?
foreach (string file in Directory.GetFiles("C:\\Scripts\\", "*.html", SearchOption.AllDirectories))
{
string contents = File.ReadAllText(file);
}
From SearchOption.AllDirectories
Includes the current directory and all its subdirectories in a search
operation. This option includes reparse points such as mounted drives
and symbolic links in the search.
Try like this;
var d = new DirectoryInfo(#"c:\scripts");
foreach(var fin d.EnumerateFiles("*.html", SearchOption.AllDirectories))
{
}
I have a path "C:\Users\Web References"
Under the "Web References" folder, i have *.wsdl file
I want to get the full filename of the *.wsdl file
Thanks!
Something like this:
var files = Directory.GetFiles("C:\\Users\\Web References", "*.wsdl", SearchOption.AllDirectories);
This will return a collection of files - there could be more than one wsdl file in the directory. Take the first:
var wsdlFile = files.FirstOrDefault();
Seeing that no-one is mentioning it: Path.GetFullPath()
First, you have to find it:
var files = Directory.GetFiles(path, "*.wsdl");
and now files will contain full paths to all WSDL files (if any) in path.
// find files by filter
var result = Directory.GetFiles("C:\\Users\\Web References\\", "*.wsdl");
//if you have only one file
return System.IO.Path.GetFileName(result[0]); // "my.wsdl"
The Path class will help you extract just the filename from a file path:
string path = #"C:\Users\Web References";
string[] files = Directory.GetFiles(path, "*.wsdl");
foreach (string filePath in files) {
string filename = Path.GetFileName(filePath); // e.g. myFile.wsdl
}
or using linq
var files = from f in Directory.GetFiles((#"C:\Users\Web References")
where f.EndsWith(".wsdl")
select f;
foreach (var file in files)
...
I need to Copy folder C:\FromFolder to C:\ToFolder
Below is code that will CUT my FromFolder and then will create my ToFolder.
So my FromFolder will be gone and all the items will be in the newly created folder called ToFolder
System.IO.Directory.Move(#"C:\FromFolder ", #"C:\ToFolder");
But i just want to Copy the files in FromFolder to ToFolder.
For some reason there is no System.IO.Directory.Copy???
How this is done using a batch file - Very easy
xcopy C:\FromFolder C:\ToFolder
Regards
Etienne
This link provides a nice example.
http://msdn.microsoft.com/en-us/library/cc148994.aspx
Here is a snippet
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
there is a file copy.
Recreate folder and copy all the files from original directory to the new one
example
static void Main(string[] args)
{
DirectoryInfo sourceDir = new DirectoryInfo("c:\\a");
DirectoryInfo destinationDir = new DirectoryInfo("c:\\b");
CopyDirectory(sourceDir, destinationDir);
}
static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)
{
if (!destination.Exists)
{
destination.Create();
}
// Copy all files.
FileInfo[] files = source.GetFiles();
foreach (FileInfo file in files)
{
file.CopyTo(Path.Combine(destination.FullName,
file.Name));
}
// Process subdirectories.
DirectoryInfo[] dirs = source.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
// Get destination directory.
string destinationDir = Path.Combine(destination.FullName, dir.Name);
// Call CopyDirectory() recursively.
CopyDirectory(dir, new DirectoryInfo(destinationDir));
}
}
Copying directories (correctly) is actually a rather complex task especially if you take into account advanced filesystem techniques like junctions and hard links. Your best bet is to use an API that supports it. If you aren't afraid of a little P/Invoke, SHFileOperation in shell32 is your best bet. Another alternative would be to use the Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory method in the Microsoft.VisualBasic assembly (even if you aren't using VB).
yes you are right.
http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx
has provided copy function ..
or you can use another function
http://msdn.microsoft.com/en-us/library/ms127960.aspx
You'll need to create a new directory from scratch then loop through all the files in the source directory and copy them over.
string[] files = Directory.GetFiles(GlobalVariables.mstrReadsWellinPath);
foreach(string s in files)
{
fileName=Path.GetFileName(s);
destFile = Path.Combine(DestinationPath, fileName);
File.Copy(s, destFile);
}
I leave creating the destination directory to you :-)
You're right. There is no Directory.Copy method. It would be a very powerful method, but also a dangerous one, for the unsuspecting developer. Copying a folder can potentionaly be a very time consuming operation, while moving one (on the same drive) is not.
I guess Microsoft thought it would make sence to copy file by file, so you can then show some kind of progress information. You could iterate trough the files in a directory by creating an instance of DirectoryInfo and then calling GetFiles(). To also include subdirectories you can also call GetDirectories() and enumerate trough these with a recursive method.
A simple function that copies the entire contents of the source folder to the destination folder and creates the destination folder if it doesn't exist
class Utils
{
internal static void copy_dir(string source, string dest)
{
if (String.IsNullOrEmpty(source) || String.IsNullOrEmpty(dest)) return;
Directory.CreateDirectory(dest);
foreach (string fn in Directory.GetFiles(source))
{
File.Copy(fn, Path.Combine(dest, Path.GetFileName(fn)), true);
}
foreach (string dir_fn in Directory.GetDirectories(source))
{
copy_dir(dir_fn, Path.Combine(dest, Path.GetFileName(dir_fn)));
}
}
}
This article provides an alogirthm to copy recursively some folder and all its content
From the article :
Sadly there is no built-in function in System.IO that will copy a folder and its contents. Following is a simple recursive algorithm that copies a folder, its sub-folders and files, creating the destination folder if needed. For simplicity, there is no error handling; an exception will throw if anything goes wrong, such as null or invalid paths or if the destination files already exist.
Good luck!
My version of DirectoryInfo.CopyTo using extension.
public static class DirectoryInfoEx {
public static void CopyTo(this DirectoryInfo source, DirectoryInfo target) {
if (source.FullName.ToLower() == target.FullName.ToLower())
return;
if (!target.Exists)
target.Create();
foreach (FileInfo f in source.GetFiles()) {
FileInfo newFile = new FileInfo(Path.Combine(target.FullName, f.Name));
f.CopyTo(newFile.FullName, true);
}
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) {
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
diSourceSubDir.CopyTo(nextTargetSubDir);
}
}
}
And use like that...
DirectoryInfo d = new DirectoryInfo("C:\Docs");
d.CopyTo(new DirectoryInfo("C:\New"));