Return file located in a specific path - c#

I wrote a method in order to return a file using the return type HttpResposeMessage. I use the below code in order to attach the file.
file.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = newFileName
};
file.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return file;
How can I specify a specific path in to the filename.
I did something like this
fileName = "C://Templates/Order.pdf"
But this renames the file name as C:_Templates_Order.pdf
What I need is to go through the path and grab the file.

You can declare a string literal by using the # symbol in front of the quotes for your string:
fileName = #"C:\templates\order.pdf"
Or you can double escape the backslash
fileName = "C:\\templates\\order.pdf"

You need to put the file name using this simbol \ instead of /
fileName = "C:\\Templates\\Order.pdf";

Related

Get File Extension C#

I have a dropdown with list of file names. When a file name is selected in the dropdown I do the following
string filename = ddl.SelectedItem.Text;
string path = "F:\\WorkingCopy\\files\\" + filename +".docx";
DownloadFile(path,filename);
In the file folder files may contain any extension . Since i have hard coded ".docx" in string path everything works fine. But I need to get the extension of the file name with the ddl.SelectedItem.Text alone. Can you tell me how to do this?
Things I have
1.) File name without extension in
string filename = ddl.SelectedItem.Text;
2.) Path where the file is located
string path = "F:\\WorkingCopy\\files\\" + filename
I am trying to get the file extension with these . Can any one suggest on this?
You can use Directory.EnumerateFiles() like this:
string path = "F:\\WorkingCopy\\files\\";
string filename = ddl.SelectedItem.Text;
string existingFile = Directory.EnumerateFiles(path, filename + ".*").FirstOrDefault();
if (!string.IsNullOrEmpty(existingFile))
Console.WriteLine("Extension is: " + Path.GetExtension(existingFile));
Directory.EnumerateFiles searches the path for files like filename.*. Path.GetExtension() returns the extension of the found file.
In general, I prefer to use EnumerateFiles() instead of GetFiles because it returns an IEnumerable<string> instead string[]. This suggests that it only returns the matching files as needed instead searching all matching files at once. (This doesn't really matter in your case, just a general note).
Use the Directory.GetFiles() method. Something like this
string[] files = Directory.GetFiles("F:\\WorkingCopy\\files\\", filename+".*");
This should get you an array of filenames with the same filename but different extensions. If you have only one, then you can always use the first one.
You can use Directory.GetFiles Method:
string result = Directory.GetFiles(path, filename + ".*").FirstOrDefault();
see here
here " * " is the WildCard and will search for the Filename starts with YourFileName.
you can achieve that with followed by line
try
{
var extensions = new List<string>();
var files = Directory.GetFiles("F:\\WorkingCopy\\files\\", filename + ".*", System.IO.SearchOption.TopDirectoryOnly);
foreach (var tmpfile in files)
extensions.Add(Path.GetExtension(tmpfile));
}
catch (Exception ex)
{
throw ex;
}
will this help you?
You can simply split them by dot, For example, try this code
string folder = #"F:\\WorkingCopy\\files\\";
var files = System.IO.Directory.GetFiles(folder, filename + ".*");
if (files.Any())
{
string ext = System.IO.Path.GetExtension(files.First()).Substring(1);
}
This code gives me result that the extension for this is txt file.

Remove Extra back slash "\" from string file path in c#

How to convert
"String path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
into
String path = #"C:\Abc\Omg\Why\Me\".
My approach is to first reverse the string and then remove all the "\" till we get first char, and the reverse it again.
How to do this in C#, is there any method for such operation?
You can just construct path using the Path static class:
string path = Path.GetFullPath(#"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\");
After this operation, variable path will contain the minimal version:
C:\Abc\Omg\Why\Me\
You can use path.TrimEnd('\\'). Have a look at the documentation for String.TrimEnd.
If you want the trailing slash, you can add it back easily.
var path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
path = path.TrimEnd('\\') + '\\';
another solution is
var path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
path = Path.GetFullPath(path);

How to get the substring after a given string

I'm new to C# and struggle with string parsing. I have a string like this:
C:\User\Max\Pictures\
And I got multiple file paths:
C:\User\Max\Pictures\car.jpg
C:\User\Max\Pictures\trains\train.jpg
How can I strip the base path from those file paths to get:
car.jpg
trains\train.jpg
Something like this failed:
string path = "C:\\User\\Max\\Pictures\\";
string file = "C:\\User\\Max\\Pictures\\trains\\train.jpg";
string newfile = file.Substring(file.IndexOf(path));
You want to get the substring of file after the length of path:
string newfile = file.Substring(path.Length);
Note that it's a good idea to use Path methods like Path.GetFileName() when dealing with file paths (though it's not good applyable to the "train" example).
The other answer would be to replace your path with an empty string :
string filePath = file.Replace(path, "");
There are special classes to handle filepaths
var filePath = new FileInfo("dd");
In filePath.Name is the filename of the file whitout directory
So for your scenario you want to strip base dir. So you can do this
var filePath = new FileInfo(#"c:\temp\train\test.xml");
var dir = filePath.FullName.Replace(#"c:\temp", String.Empty);

Do I use a regular expression on this file path?

I have to strip a file path and get the parent folder.
Say my path is
\\ServerA\FolderA\FolderB\File.jpg
I need to get
File Name = File.jog
Folder it resides in = FolderB
And parent folder = FolderA
I always have to go 2 levels up from where the file resides.
Is there an easier way or is a regular expression the way to go?
FileInfo is your friend:
using System;
using System.IO;
class Test
{
static void Main(string[] args)
{
string file = #"\\ServerA\FolderA\FolderB\File.jpg";
FileInfo fi = new FileInfo(file);
Console.WriteLine(fi.Name); // Prints File.jpg
Console.WriteLine(fi.Directory.Name); // Prints FolderB
Console.WriteLine(fi.Directory.Parent.Name); // Prints FolderA
}
}
string fileName = System.IO.Path.GetFileName(path);
string parent = System.IO.Path.GetDirectoryName(path);
string parentParent = System.IO.Directory.GetParent(parent);
Check out the Directory class (better choice than DirectoryInfo in this case). It does everything you need. You should not use a regex or any other parsing technique.
var fi = new FileInfo(#"\\ServerA\FolderA\FolderB\File.jpg");
fi.Name
fi.Directory.Name
fi.Directory.Parent.Name
You have a few options to do this actually which use actual .net objects instead of regex.
You can use the FileInfo:
FileInfo fileInfo = new FileInfo(#"\\ServerA\FolderA\FolderB\File.jpg");
fileInfo.Name //will give you the file name;
DirectoryInfo directory = fileInfo.Directory; //will give you the parent folder of the file (FolderB);
directory.Parent; //will give you this directories parent folder (FolderA)
If you know for sure that you are always dealing with a file and two directories, try using split:
string s = #"\\ServerA\FolderA\FolderB\File.jpg";
string[] parts = s.Split('\'); // might need '\\'
string file = parts[parts.Length];
string parentDir = parts[parts.Length - 1];
string grandParentDir = parts[parts.Length - 2];

Concatenating Environment.CurrentDirectory with back path

If i have the following directory structure:
Project1/bin/debug
Project2/xml/file.xml
I am trying to refer to file.xml from Project1/bin/debug directory
I am essentially trying to do the following:
string path = Environment.CurrentDirectory + #"..\..\Project2\xml\File.xml":
what is the correct syntax for this?
It's probably better to manipulate path components as path components, rather than strings:
string path = System.IO.Path.Combine(Environment.CurrentDirectory,
#"..\..\..\Project2\xml\File.xml");
Use:
System.IO.Path.GetFullPath(#"..\..\Project2\xml\File.xml")
string path = Path.Combine( Environment.CurrentDirectory,
#"..\..\..\Project2\xml\File.xml" );
One ".." takes you to bin
Next ".." takes you to Project1
Next ".." takes you to Project1's parent
Then down to the file
Please note that using Path.Combine() might not give you the expected result, e.g:
string path = System.IO.Path.Combine(#"c:\dir1\dir2",
#"..\..\Project2\xml\File.xml");
This results in in the following string:
#"c:\dir1\dir2\dir3\..\..\Project2\xml\File.xml"
If you expect the path to be "c:\dir1\Project2\xml\File.xml", then you might use a method like this one instead of Path.Combine():
public static string CombinePaths(string rootPath, string relativePath)
{
DirectoryInfo dir = new DirectoryInfo(rootPath);
while (relativePath.StartsWith("..\\"))
{
dir = dir.Parent;
relativePath = relativePath.Substring(3);
}
return Path.Combine(dir.FullName, relativePath);
}

Categories