I'm unable to reference an uploaded file - c#

Sorry if this is a simple question but I'm still not to competent at coding. Via ASP.net c# I upload a file to Uploads with an UploadHandler.ashx which is working fine. Then I try to reference the file. Before referencing it I check to see if the file exists with
if (File.Exists(filePath))
{
Do stuff;
}
else
{
Do other stuff;
}
When debugging the filePath is showing as "../Uploads/P3301_5_40_4.bin" which is what I am expecting but the if file exists is returning false. Am I entering the file path with an incorrect syntax or is there something else I am messing up? I confirmed the file is there.

File.Exists is probably looking for the physical path to the file on the server. Try using Server.MapPath which maps the virtual path in your website to the physical path on the server.
string physicalPath = Server.MapPath(filePath);
if (System.IO.File.Exists(physicalPath))
{
// do stuff
}
else
{
// handle error
}

You should convert filePath using something like this:
filePath = HttpContext.Current.Server.MapPath(filePath);

Related

UnauthorizedAccessException when saving file, but can create a directory

I'm trying to save a file to the disk but I get UnauthorizedAccessException.
The error says I have to get the right permissions on the folder, and I've tried every possible user I can find but it doesn't work.
Tried the following users
Network
Network Services
IUSR
IUSR_[Computername]
And given the full rights without it working.
What I find really strange is that I create a directory before I try to save the file and that works perfectly, it's when trying to save a file to that new directory that I get the UnautorhizedAccessException.
The code is the following:
[HttpPost]
public ActionResult Images(HttpPostedFileBase file, string boatId)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Images/" + boatId));
Directory.CreateDirectory(path);
file.SaveAs(path);
}
return View($"Filen på {boatId} har laddats upp");
}
Any ideas at what I'm missing?
Turns out what I was trying to do was saving the folder and not the file, I forgot to combine the fileName with the path.
Changed the Save part to the following:
file.SaveAs(Path.Combine(path, fileName));
Which solved the whole thing for me.

Wait for .zip file to extract before copying it's contents elsewhere programmaticaly

I'm trying to write a small console app tool that unzips an archive containing multiple files/folders/other archives and arrange it's contents in another way.
I unzip the root file with ZipFile.ExtractToDirectory method from System.IO.Compression.FileSystem library:
public static void UnzipPackage(string packagePath, string targetPath)
{
try
{
ZipFile.ExtractToDirectory(packagePath, targetLocation);
Console.WriteLine("Unzipping file {0} complete.", packagePath);
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("Directory was not found.");
}
catch (FileNotFoundException)
{
Console.WriteLine("File was not found.");
}
}
After running this method on my package, I want to copy a file which was in this package in a subfolder.
According to MSDN I do this:
if (!Directory.Exists(targetLocation + #"READY\PHOTO"))
{
Directory.CreateDirectory(targetLocation + #"\READY\PHOTO");
}
if (Directory.Exists(targetLocation + #"\MAIN\PHOTO"))
{
string[] files = Directory.GetFiles(targetLocation + #"\MAIN\PHOTO");
foreach (var file in files)
{
string fileName = Path.GetFileName(file);
string destFile = Path.Combine(targetLocation + #"\MAIN\PHOTO", fileName);
File.Copy(file, destFile, true);
}
}
Both MAIN and READY are my subdirectories where whole package goes ("main") and sorted files go ("ready").
However, when running this, the zip file is not yet unzipped - an exception occurs showing it can't access the file specified even though it grabbed it's name from Directory.GetFiles(). The folder created when unzipping the zip file shows only after I terminate my console app (no wonder it can't access it).
So the big question is - how can I wait for the unzipped folder to show up? I tried using Thread.Sleep(), but it doesn't affect the flow anyhow - an exception still occurs, and the folder shows only after I terminate the app.
Your error is here:
string destFile = Path.Combine(targetLocation + #"\MAIN\PHOTO", fileName);
Should be:
string destFile = Path.Combine(targetLocation + #"\READY\PHOTO", fileName);
You're attempting to copy the file to the same location.
I'm assuming your getting an IOException something like "The process cannot access the file...because it is being used by another process."
It looks to me that there is a problem in your copy method. It looks like your from and to paths are essentially the same. So the system cannot overwrite the file, because you currently have it open for reading.
Just to be clear - the issue is not related to unzipping! In the example you have written the variable file and destFile are going to be the same - and they need to be different.

Argument Null Exception error when trying to create a Text File

Problem:
I am trying to create a text file from a web service (local host), but on creation it gets the null argument error for path location. Now I am still using 2012 and was under the impression the code I gave would return the path name, but just returns null.
Aim:
Create a new file if one doesn't exist.
Get the path of the file for future use.
Question:
What are the visual studio 2012 C# methods for creating a text file? I find allot of sources but the code doesn't seem to work with 2012.
My Code:
//Create a file name for the path
string path = System.IO.Path.Combine(CurrentDirectory, "textFile.txt");
//Check if it exist, if not then create the File
//This is the recommended code by Microsoft
if (!System.IO.File.Exists(path))
{
System.IO.File.Create(path);
}
Get the file path using Server.Map path
string FolderPath = Server.MapPath("~/App_Data");
string file = Path.Combine(FolderPath, "textFile.txt");
//Check if it exist, if not then create the File
//This is the recommended code by Microsoft
if (!System.IO.File.Exists(file))
{
System.IO.File.Create(file);
}
Also check if the IIS user have permission to write on that folder (Add permission to the application pool user)
If you are trying to write something on a txt file, these piece of code does. No need to create a file if it is not exist. These code will create a file automatically if it not exists.
public static void LogMessage(string sFilePath, string sMsg)
{
using (StreamWriter sw = File.AppendText(sFilePath))
{
sw.WriteLine(string.Format(#"{0} : {1}", DateTime.Now.ToLongTimeString(), sMsg));
}
}
Are you sure CurrentDirectory value is right?
If you want visit current Web Service root dir can use like AppDomain.CurrentDomain.BaseDirectory.

How to save a text file in Hard Disk using C#

I'm creating a logger for my app and I'm stuck with a problem I need to save my log file in my C drive but when I'm executing the Code its give me an error "Given Path Format Is Not Supported" My current code is given below
string path="C:\\Logger\\"+DateTime.Now.Date.ToString()+".txt";
public void CreateDirectory()
{
if(!File.Exists(path))
{
File.Create(path);
}
}
any solutions????
You're going to have to format the date:
string path="C:\\Logger\\"+DateTime.Now.Date.ToString("yyyy_MM_dd")+".txt";
because the operating system isn't going to accept something like this:
C:\Logger\07/27/2013.txt
Now, for future reference, consider using Path.Combine to build your paths:
var path = Path.Combine("C:\\Logger",
DateTime.Now.Date.ToString("yyyy_MM_dd"),
".txt");
You won't have to determine when to provide back slashes and when not to. If there isn't one, it will be appended for you.
Finally, you may experience problems if the directory doesn't exist. Something you can do to mitigate that is this:
var path = ...
var dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
{
Directory.Create(dir);
}
But even then, you can run into permissions issues during runtime.
Check that the result of this: DateTime.Now.Date.ToString() is accepted by the operating system.

User Permissions issue

I am using Visual Studio C# to parse an XML document for a file location from a local search tool I am using. Specifically I am using c# to query if the user has access to certain files and hide those to which it does not have access. I seem to have files that should return access is true however because not all files are local (IE some are web files without proper names) it is not showing access to files it should be showing access to. The error right now is caused by a url using .aspx?i=573, is there a work around or am I going to have to just remove all of these files... =/
Edit: More info...
I am using right now....
foreach (XmlNode xn in nodeList)
{
string url = xn.InnerText;
//Label1.Text = url;
try
{ using (FileStream fs = File.OpenRead(url)) { }
}
catch { i++; Label2.Text = i.ToString(); Label1.Text = url; }
}
The issue is, when it attempts to open files like the ....aspx?i=573 it puts them in the catch stack. If I attempt to open the file however the file opens just fine. (IE I have read access but because of either the file type or the append of the '?=' in the file name it tosses it into the unreadable stack.
I want everything that is readable either via url or local access to display else it will catch the error files for me.
I'm not sure exactly what you are trying to do, but if you only want the path of a URI, you can easily drop the query string portion like this:
Uri baseUri = new Uri("http://www.domain.com/");
Uri myUri = new Uri(baseUri, "home/default.aspx?i=573");
Console.WriteLine(myUri.AbsolutePath); // ie "home/default.aspx"
You cannot have ? in file names in Windows, but they are valid in URIs (that is why IE can open it, but Windows cannot).
Alternatively, you could just replace the '?' with some other character if you are converting a URL to a filename.
In fact thinking about it now, you could just check to see if your "document" was a URI or not, and if it isn't then try to open the file on the file system. Sounds like you are trying to open any and everything that is supplied, but it wouldn't hurt to performs some checks on the data.
private static bool IsLocalPath(string p)
{
return new Uri(p).IsFile;
}
This is from Check if the path input is URL or Local File it looks like exactly what you are looking for.
FileStream reads and writes local files. "?" is not valid character for local file name.
It looks like you want to open local and remote files. If it is what you are trying to do you should use approapriate metod of downloading for each type - i.e. for HTTP you WebRequest or related classes.
Note: it would be much easier to answer if you'd say: when url is "..." File.OpenRead(url) failes with exception, mesasge "...".

Categories