Remove Filepath in GridFS - c#

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.

Related

How to change .pbix filename and replace by different .pbix file with different name by using C#?

To prevent lose of setting like scheduled refresh time, are there any ways to change the .pbix filename (i.e. report name in PowerBI console)?
Thus, if want to change the content and filename, how to do that?
Below is my current code that can only base on workspaceId and datasetName(.pbix filename).
using var client = new PowerBIClient(new Uri(_apiUrl), _tokenCredentials) {HttpClient = {Timeout = TimeSpan.FromMinutes(5)}};
// Import PBIX file from the file stream with Overwrite Method present
import = await client.Imports.PostImportWithFileAsync(new Guid(workspaceId), fileStream, datasetName, ImportConflictHandlerMode.CreateOrOverwrite, cancellationToken: cancellationToken);
You can use CloneReportRequest API to save your report.
You need to provide the name, targetWorkspaceId and targetModelId
public CloneReportRequest (string name = default, string targetWorkspaceId = default, string targetModelId = default);
Reference:
CloneReportRequest Constructor (Microsoft.PowerBI.Api.V2.Models) - Azure for .NET Developers | Microsoft Docs

How to get a specific file from directory in 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");

How to convert path with default share [\\{host}\c$\...] to default path [c:\...]

How to convert a path defined through a default share of remote host like
\\{host}\c$\SomeFolder\SomeDeeperFolder
into a local path notation like:
c:\SomeFolder\SomeDeeperFolder
I can try splitting the original path and get the host or drive agnostic path and then concat with C:\ like follows, but I seek for a kind of built-in class/method to achieve that conversion neatlier:
var defaultSharedPath = "\\\\someremotehostname\\c$\\SomeFolder\\SomeDeeperFolder";
// The drive is always c:\ in my case, so I can directly split with it
var path = defaultSharedPath.Split(new string[] { "\\c$\\" }, StringSplitOptions.None).ToList().Last();
var localLikePath = "C:\\" + path;
Console.WriteLine(localLikePath);

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

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