How to get a specific file from directory in C# - c#

Using Directory.GetFiles() returns all the files in the directory as follows:
var sqlFiles = Directory.GetFiles($"{AppDomain.CurrentDomain.BaseDirectory}Content\\DbScripts\\","*.sql");
Actually I need a specific file from that directory. What I have tried so far as follows but don't work!
var localizationSqlFile = Directory.GetFiles($"{AppDomain.CurrentDomain.BaseDirectory}Content\\DbScripts\\Localizations.sql").FirstOrDefault();
It throws expection:
The directory name is invalid.\r\n
Is there any method in C# to get a single file from a directory? If not then what will be most efficient way?

If you want to get the bytes of a certain file and you already have the full path, you can use the static method File.ReadAllBytes
var fileBytes = File.ReadAllBytes(myPath);
If you want to get file infos, you can create a new FileInfo object
var fileInfo = new FileInfo(myPath);
If you just want to check, if a file exists, you can also use the method File.Exist
if (File.Exists(myPath))

You can get the file from your sqlFiles returned
var sqlFiles = Directory.GetFiles($"{AppDomain.CurrentDomain.BaseDirectory}Content\\DbScripts\\","*.sql");
var yourFile = sqlFiles.FirstOrDefault(x=> Path.GetFileName(x) == "Localizations.sql");

Related

C# copy last file from a folder into another generated folder

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

how to verify if an input read from console is a file name or a file full path

I have a console application in C# and I would like to load an xml file, the path to the file is provided via console.readline(). But, I would like to load the file from the provided path but if the user only provides the name of the file I would like to search for it in the local folder from where the application is running. How can I know when I get only a file name as an input or a file full path.
I managed that using: var isFileNameOnly = ((xmlFilePath.IndexOf("\\")) == -1);
But this ugly and probably very buggy.
Full code:
var xmlFilePath = Console.ReadLine();
var xmlFile = new XmlDocument();
var isFileNameOnly = ((xmlFilePath.IndexOf("\\")) == -1);
try
{
if (isFileNameOnly)
{
xmlFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, xmlFilePath);
}
xmlFile.Load(xmlFilePath);
}
Thx
You can check if the file name entered by user actually exists using Exists() method. If it returns true load the file.
File.Exists(xmlFilePath)
Also XmlDocument.Load() if provided only file name will try to find the file in the BaseDirectory itself. So if file.Exists() return true you can assume XmlDocument.Load will load it whether it is local or absolute path.
This will return false:
bool isFolder = Path.IsPathRooted(#"Text.txt");
This will return true:
bool isFolder = Path.IsPathRooted(#"C:\Text");
Your approach is the same that I would have chosen. If the param doesn't contain any directory delimiter char, then it must be a filename only. Maybe it would be a little more elegant if you did it like this:
bool isFileNameOnly = !xmlFilePath.Contains(Path.DirectorySeparatorChar.ToString());

c# .dat file assign to variable

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; }
}

Remove Filepath in GridFS

I am using the official c# driver for MongoDB and when I upload a file, the metadata contains the filename WITH the path, which is not what I would like:
var gfs = new MongoGridFS(database);
var gfsi = gfs.Upload("c:\a.pdf");
The resulting metadata is:
"_id" ...
"filename" : "c:\\a.pdf",
...
Is it possible to remove the path oder just write the filename?
The MongoGridFS class exposes multiple overloads for the Upload and Download methods, including one in which you can specify differing remote/local paths.
e.g.
var gfs = new MongoGridFS
gfs.Upload(#"c:\a.pdf", "a.pdf");
gfs.Download(#"c:\b.pdf", "a.pdf");
The filename for the GridFS object always refers to the remote filename you set here and the original filename would be otherwise lost.

How to find the extension of a file in C#?

In my web application (asp.net,c#) I am uploading video file in a page but I want to upload only flv videos. How can I restrict when I upload other extension videos?
Path.GetExtension
string myFilePath = #"C:\MyFile.txt";
string ext = Path.GetExtension(myFilePath);
// ext would be ".txt"
You may simply read the stream of a file
using (var target = new MemoryStream())
{
postedFile.InputStream.CopyTo(target);
var array = target.ToArray();
}
First 5/6 indexes will tell you the file type. In case of FLV its 70, 76, 86, 1, 5.
private static readonly byte[] FLV = { 70, 76, 86, 1, 5};
bool isAllowed = array.Take(5).SequenceEqual(FLV);
if isAllowed equals true then its FLV.
OR
Read the content of a file
var contentArray = target.GetBuffer();
var content = Encoding.ASCII.GetString(contentArray);
First two/three letters will tell you the file type.
In case of FLV its "FLV......"
content.StartsWith("FLV")
At the server you can check the MIME type, lookup flv mime type here or on google.
You should be checking that the mime type is
video/x-flv
If you were using a FileUpload in C# for instance, you could do
FileUpload.PostedFile.ContentType == "video/x-flv"
I'm not sure if this is what you want but:
Directory.GetFiles(#"c:\mydir", "*.flv");
Or:
Path.GetExtension(#"c:\test.flv")
In addition, if you have a FileInfo fi, you can simply do:
string ext = fi.Extension;
and it'll hold the extension of the file (note: it will include the ., so a result of the above could be: .jpg .txt, and so on....
string FileExtn = System.IO.Path.GetExtension(fpdDocument.PostedFile.FileName);
The above method works fine with the Firefox and IE: I am able to view all types of files like zip,txt,xls,xlsx,doc,docx,jpg,png.
But when I try to find the extension of file from Google Chrome, I fail.
EndsWith()
Found an alternate solution over at DotNetPerls that I liked better because it doesn't require you to specify a path. Here's an example where I populated an array with the help of a custom method
// This custom method takes a path
// and adds all files and folder names to the 'files' array
string[] files = Utilities.FileList("C:\", "");
// Then for each array item...
foreach (string f in files)
{
// Here is the important line I used to ommit .DLL files:
if (!f.EndsWith(".dll", StringComparison.Ordinal))
// then populated a listBox with the array contents
myListBox.Items.Add(f);
}
It is worth to mention how to remove the extension also in parallel with getting the extension:
var name = Path.GetFileNameWithoutExtension(fileFullName); // Get the name only
var extension = Path.GetExtension(fileFullName); // Get the extension only
You will not be able to restrict the file type that the user uploads at the client side[*]. You'll only be able to do this at the server side. If a user uploads an incorrect file you will only be able to recognise that once the file is uploaded uploaded. There is no reliable and safe way to stop a user uploading whatever file format they want.
[*] yes, you can do all kinds of clever stuff to detect the file extension before starting the upload, but don't rely on it. Someone will get around it and upload whatever they like sooner or later.
You can check .flv signature. You can download specification here:
http://www.adobe.com/devnet/flv/
See "The FLV header" chapter.
private string GetExtension(string attachment_name)
{
var index_point = attachment_name.IndexOf(".") + 1;
return attachment_name.Substring(index_point);
}
This solution also helps in cases of more than one extension like "Avishay.student.DB"
FileInfo FileInf = new FileInfo(filePath);
string strExtention = FileInf.Name.Replace(System.IO.Path.GetFileNameWithoutExtension(FileInf.Name), "");
Path.GetExtension(file.FileName)) will get you the file name
Im also sharing a test code if someone needs to test and ge the extention or name.
Forming a text file with name test.txt and checking its extention in xUnit.
[Fact]
public void WrongFileExtention_returnError()
{
//Arrange
string expectedExtention = ".csv";
var content = "Country,Quantity\nUnited Kingdom,1";
var fileName = "test.csv";
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(content);
writer.Flush();
stream.Position = 0;
//Act
IFormFile file = new FormFile(stream, 0, stream.Length, "", fileName);
//Assert
Assert.Equal(expectedExtention, Path.GetExtension(file.FileName));
}
Return true as the expected and the filename extention is name.
Hope this helps someone :).
I know this is quite an old question but here's a nice article on getting the file extension as well as a few more values:
Get File Extension in C#
I Hope That Helps :-)!

Categories

Resources