Check FileName From HttpHostedFileBase is File Name or File Path - c#

I am developing an application which store filename in database. For Mozilla & Chrome it is showing FileName only but in IE it is showing full path of file. Now I want to check whether given filename is filename or filepath. Is there any way to do it?
Here is my code:
public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
{
byte[] image = null;
var file = attachments.First();
// Some browsers send file names with full path. We only care about the file name.
string filePath = Server.MapPath(General.FaxFolder + "/" + file.FileName);
file.SaveAs(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
using (BinaryReader br = new BinaryReader(fs))
{
image = br.ReadBytes((int)fs.Length);
}
TempData["Image"] = image;
System.IO.File.Delete(filePath);
return Json(new { status = "OK", imageString = Convert.ToBase64String(image) }, "text/plain");
}

Well,If you go with getting filename only in any browser then you should write
Path.GetFileName(e.fileName);
It will return filename only in any browser
Thanks

Instead of check whether the file has a path or not, what you can do is to just use
GetFileName(path);method

Related

Getting a file from "file://A/"

How can I get a file from external path same as "file://A/B/C/D/"
In local machine I have access to the path of "file://" but the user has not access.
Now I want to read some files from "file://A/B/C/D/" and make downloadable for user.
How can I do it?
(current directory is "https://localhost:44331/")
public async Task<IActionResult> DownloadDocument(string berichtsnummer)
{
var constantPath = "file://A/B/C/D/";
using (FileStream fileStream = System.IO.File.OpenRead(constantPath))
{
MemoryStream memStream = new MemoryStream();
memStream.SetLength(fileStream.Length);
fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
return File(fileStream, "application/octet-stream");
}
}
when I click to download link, I get this error:
"IOException: The syntax for filename, directory name, or volume label
is incorrect:"
[
A view of path "file://A/B/C/D/":
A local file path is not "file://". You can read the file normally using the local file path as
var path = "C:\\...";
and then send to content to the client browser.
If the file is not on the local machine, the only way is to access it using a network share. You can then use UNC paths, like
var path = #"\\Server\Path\...";
That's important to change the constantPath to "\\\\A\\B\\C\\D\\"
private string[] GetListOfDocumentLink()
{
string path = string.Empty;
string constantPath = "\\\\A\\B\\C\\D\\";
string folderName = string.Empty;
string year = string.Empty;
// determine folderName and year.
path = constantPath
+ Path.DirectorySeparatorChar.ToString()
+ folderName
+ Path.DirectorySeparatorChar.ToString()
+ year;
var filter = Berichtsnummer + "*.pdf";
string[] allFiles = Directory.GetFiles(path, filter);
return allFiles;
}
Now you can send the path to DownloadDocument method:
public async Task<IActionResult> DownloadDocument(string path)
{
byte[] berichtData = null;
FileInfo fileInfo = new FileInfo(path);
long berichtFileLength = fileInfo.Length;
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
berichtData = br.ReadBytes((int)berichtFileLength);
return File(berichtData, MimeTypeHelper.GetMimeType("pdf"));
}

Asp .NET Read a file from a tar.gz archive

I have some files inside in one .tar.gz archive. These files are on a linux server.How can I read from a specific file inside this archive if I know it's name?
For reading direct from the txt file, I used the following code:
Uri urlFile = new Uri("ftp://" + ServerName + "/%2f" + FilePath + "/" + fileName);
WebClient req = new WebClient() { Credentials=new NetworkCredential("user","psw")};
string result = req.DownloadString(urlFile);
It's possible to read this file without copying the archive on the local machine, something like the code above?
I found a solution. Maybe this can help you guys.
// archivePath="ftp://myLinuxServer.com/%2f/move/files/archive/20170225.tar.gz";
public static string ExtractFileFromArchive(string archivePath, string fileName)
{
string stringFromFile="File not found";
WebClient wc = new WebClient() { Credentials = cred, Proxy= webProxy }; //Create webClient with all necessary settings
using (Stream source = new GZipInputStream(wc.OpenRead(archivePath))) //wc.OpenRead() create one stream with archive tar.gz from our server
{
using (TarInputStream tarStr =new TarInputStream(source)) //TarInputStream is a stream from ICSharpCode.SharpZipLib.Tar library(need install SharpZipLib in nutgets)
{
TarEntry te;
while ((te = tarStr.GetNextEntry())!=null) // Go through all files from archive
{
if (te.Name == fileName)
{
using (Stream fs = new MemoryStream()) //Create a empty stream that we will be fill with file contents.
{
tarStr.CopyEntryContents(fs);
fs.Position = 0; //Move stream position to 0, in order to read from beginning
stringFromFile = new StreamReader(fs).ReadToEnd(); //Convert stream to string
}
break;
}
}
}
}
return stringFromFile;
}

changing a received file location in c# socket

I have created a TCP server in c# which receives a file from a client and keeps it in the current directory. The code segment which does this is as follows:
using (FileStream fStream = new FileStream(Path.GetFileName(cmdFileName), FileMode.Create))
{
fStream.Write(buffer, 0, buffer.Length);
fStream.Flush();
fStream.Close();
}
Console.WriteLine("File received and saved in " + Environment.CurrentDirectory);
where cmdFileName is the received filename.
Now I have created a folder named "test" inside the current directory using the following code:
string root = Environment.CurrentDirectory;
string folder = Path.Combine(root,"test");
if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
I want to keep the received file inside the "test" folder. I need to make change to the following line of my previous code segment:
using (FileStream fStream = new FileStream(Path.GetFileName(cmdFileName), FileMode.Create))
But what change will I have to make?
You are using Path.Combine to get the path of the new test directory--you just need to use it again to find the path of the cmdFileName file inside the test directory:
string cmdFilePath = Path.Combine(folder, Path.GetFileName(cmdFileName));
using (FileStream fStream = new FileStream(cmdFilePath, FileMode.Create))
After this code:
string root = Environment.CurrentDirectory;
string folder = Path.Combine(root,"test");
if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
Add another usage of the Path.Combine since you want to attach the path folder to the file cmdFileName:
string fullFilePath = Path.Combine(folder, Path.GetFileName(cmdFileName));
using (FileStream fStream = new FileStream(fullFilePath, FileMode.Create))
{
...
}
Console.WriteLine("File received and saved in " + fullFilePath);
Also you should want to do it inside a try block in order to announce that it succeeded only if it really did:
try
{
using (FileStream fStream = new FileStream(fullFilePath, FileMode.Create)) //Exception accessing the file will prevent the console writing.
{
...
}
Console.WriteLine("File received and saved in " + fullFilePath);
}
catch (...){...Console.WriteLine("Could not write to file " + fullFilePath);...}

Save an image on asp.net server

I'm trying to save a piture recovered from a byte[] on the asp.net server. Here is my code :
MemoryStream ms = new MemoryStream(cli.LOGO, 0, cli.LOGO.Length);
ms.Write(cli.LOGO, 0, cli.LOGO.Length);
string thePath = Server.MapPath("~/App_Data");
string wholePath = thePath + "\\logo.jpg";
FileStream fs = new FileStream(wholePath, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(cli.LOGO);
bw.Close();
Where cli.LOGO is a byte array. I'm just trying to save it as a .jpg image in my App_Data folder (or anything else of course) but... It's doing nothing. cli.LOGO is not empty, but the file is not created... Why so ? Is it the proper way to save an image ? Thanks !
Try like this which is a bit shorter than your code:
string path = Server.MapPath("~/App_Data/logo.jpg");
File.WriteAllBytes("file", cli.LOGO);
try doing this
if (Request.Files["Photo"] != null)
{
string path = "/uploads/" + DateTime.Now.Ticks.ToString() + "_" + Request.Files["Photo"].FileName;
Request.Files["Photo"].SaveAs(Server.MapPath(path));
SP.PhotoPath = path;
//The MapPath method maps the specified relative or virtual path to the
//corresponding physical directory on the server.
}

File being used (without opening it) c#

I got a strange error with this program, It download a photo from internet, then I convert it to .jpeg and then I delete the first photo (in .png).
But i got an error: File is being used by another process. Why is happening this? I didn't open the file, and nobody is using it.
string outFile;
outFile = Path.GetTempFileName();
try
{
webClient.DownloadFile(foto, outFile);
if (foto.Substring(foto.Length - 3) == "png")
{
System.Drawing.Image image1 = System.Drawing.Image.FromFile(outFile);
foto = foto.Remove(foto.Length - 3) + "jpg";
string outFile2 = Path.GetTempFileName();
image1.Save(outFile2, System.Drawing.Imaging.ImageFormat.Jpeg);
System.IO.File.Delete(outFile);
outFile = outFile2;
}
}
FromFile is keeping the file open, you have to use something like this:
// Load image
FileStream filestream;
filestream = new FileStream("Filename",FileMode.Open, FileAccess.Read);
currentImage = System.Drawing.Image.FromStream(filestream);
filestream.Close();
The system.Drawing.Image is holding on to the file, Just wrap the image1 in a using statement.
string foto = "http://icons.iconarchive.com/icons/mazenl77/I-like-buttons/64/Style-Config-icon.png";
string outFile = Path.GetTempFileName();
WebClient webClient = new WebClient();
try
{
webClient.DownloadFile(foto, outFile);
if (Path.GetExtension(foto).ToUpper() == ".PNG")
{
string outFile2 = Path.GetTempFileName();
using (System.Drawing.Image image1 = System.Drawing.Image.FromFile(outFile))
{
image1.Save(outFile2, System.Drawing.Imaging.ImageFormat.Jpeg);
}
System.IO.File.Delete(outFile);
}
}

Categories