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 :-)!
Related
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");
I am using ServiceStack for a simple web application. The main purpose is to let a user download a file. I am using an HttpResult as follows:
public class FileDownloadService : Service
{
public object Any()
{
string fileFullPath = "...";
string mimeType = "application/pdf";
FileInfo fi = new FileInfo(fileFullPath);
byte[] reportBytes = File.ReadAllBytes(fi.FullName);
result = new HttpResult(reportBytes, mimeType);
return result;
}
}
This opens a dialog in the user's browser and the user can specify where to save the file. A default name is specified, which is the name of the restPath of ServiceStack.
My question is: is it possible to specify a custom file name for when the user chooses to save (changing the default one)? I tried to work with HttpResult properties, but no luck.
Thanks in advance!
You should set the 'Content-Disposition' header on the HTTP result. That allows to set the filename:
public object Any()
{
string fileFullPath = "...";
string mimeType = "application/pdf";
FileInfo fi = new FileInfo(fileFullPath);
byte[] reportBytes = File.ReadAllBytes(fi.FullName);
result = new HttpResult(reportBytes, mimeType);
result.Headers.Add("Content-Disposition", "attachment;filename=YOUR_NAME_HERE.pdf;");
return result;
}
I have found the solution. I was deceived by the readonly properties of the HttpResult.
In order to change the default file name, I discovered that I have to add the following line, that treats the content-disposition:
result.Headers[HttpHeaders.ContentDisposition] = "attachment; filename=\"UserSurname_UserName.pdf\"";
Thank you all for your time!
If I understood your question correctly, what you want is the user wants to rename the file. This is nothing to do with the server. The user has to do some changes in the brwoser he is uses.
e.g Firefox - Tools > Options > General
Then check the "Always ask me where to save files"
Chrome - Settings > Downloads
Then check the "Ask where to save each file before "
Then it will open file browser where to save, you may change your file name what ever your wanted
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; }
}
I am trying to get the last modified date from a file, but need its path? Could someone please show me how i can get the file path?
[HttpGet]
public string uploadfile(string token, string filenameP, DateTime modDate, HttpPostedFileBase file)
{
MemoryStream target = new MemoryStream();
file.InputStream.CopyTo(target);
byte[] data = target.ToArray();
//ModDate = File.GetLastWriteTimeUtc("Path");
}
You are creating a new file on the server when you upload. The last modified date will be "now" (the time the file is created). There is no way to snoop the user's machine to get this information (which is not part of the file itself). Can't be done with an HTTP form upload.
Now, some file types may contain metadata in the file which may have pertinent information. If you know the file type and it does contain such metadata then you can open the file and have a look.
You just don't. Most (if not all) browsers do not provide this information for security reasons in internet sceanrios.
You can read date by javascript (HTML5) and send it as hidden input field of form.
Something like
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push(f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() );
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
http://www.html5rocks.com/en/tutorials/file/dndfiles/
I am currently working with SharpZipLib under .NET 2.0 and via this I need to compress a single file to a single compressed archive. In order to do this I am currently using the following:
string tempFilePath = #"C:\Users\Username\AppData\Local\Temp\tmp9AE0.tmp.xml";
string archiveFilePath = #"C:\Archive\Archive_[UTC TIMESTAMP].zip";
FileInfo inFileInfo = new FileInfo(tempFilePath);
ICSharpCode.SharpZipLib.Zip.FastZip fZip = new ICSharpCode.SharpZipLib.Zip.FastZip();
fZip.CreateZip(archiveFilePath, inFileInfo.Directory.FullName, false, inFileInfo.Name);
This works exactly (ish) as it should, however while testing I have encountered a minor gotcha. Lets say that my temp directory (i.e. the directory that contains the uncompressed input file) contains the following files:
tmp9AE0.tmp.xml //The input file I want to compress
xxx_tmp9AE0.tmp.xml // Some other file
yyy_tmp9AE0.tmp.xml // Some other file
wibble.dat // Some other file
When I run the compression all the .xml files are included in the compressed archive. The reason for this is because of the final fileFilter parameter passed to the CreateZip method. Under the hood SharpZipLib is performing a pattern match and this also picks up the files prefixed with xxx_ and yyy_. I assume it would also pick up anything postfixed as well.
So the question is, how can I compress a single file with SharpZipLib? Then again maybe the question is how can I format that fileFilter so that the match can only ever pick up the file I want to compress and nothing else.
As an aside, is there any reason as to why System.IO.Compression not include a ZipStream class? (It only supports GZipStream)
EDIT : Solution (Derived from accepted answer from Hans Passant)
This is the compression method I implemented:
private static void CompressFile(string inputPath, string outputPath)
{
FileInfo outFileInfo = new FileInfo(outputPath);
FileInfo inFileInfo = new FileInfo(inputPath);
// Create the output directory if it does not exist
if (!Directory.Exists(outFileInfo.Directory.FullName))
{
Directory.CreateDirectory(outFileInfo.Directory.FullName);
}
// Compress
using (FileStream fsOut = File.Create(outputPath))
{
using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fsOut))
{
zipStream.SetLevel(3);
ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(inFileInfo.Name);
newEntry.DateTime = DateTime.UtcNow;
zipStream.PutNextEntry(newEntry);
byte[] buffer = new byte[4096];
using (FileStream streamReader = File.OpenRead(inputPath))
{
ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(streamReader, zipStream, buffer);
}
zipStream.CloseEntry();
zipStream.IsStreamOwner = true;
zipStream.Close();
}
}
}
This is an XY problem, just don't use FastZip. Follow the first example on this web page to avoid accidents.