Trying to upload an excel file. The code works fine in chrome & firefox. It throws up the above error in IE8. How can I fix this.
private const string ExcelUploadPath = "~/UploadedFiles/";
private void SomeFunction()
{
string dirPath = Server.MapPath(ExcelUploadPath);
string ErrorMsg = SaveUploadedFile(fupCtrl, dirPath)
}
private string SaveUploadedFile(FileUpload fupCtrl, string dirPath)
{
try
{
string sFileName = "";
Random ranObj = null;
int nRandomNum = 0;
ranObj = new Random();
nRandomNum = ranObj.Next();
sFileName = fupCtrl.PostedFile.FileName;
sFileName = sFileName.Substring(0, sFileName.LastIndexOf(".") - 1);
sFileName = sFileName + "_" + nRandomNum.ToString();
sFileName = sFileName +
fupCtrl.FileName.Substring(fupCtrl.FileName.LastIndexOf("."));
fupCtrl.SaveAs(dirPath + sFileName); //exception here
return sFileName;
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
The FileUpload.PostedFile.FileName returns the full file name on the client (including path)
The Path class offers numerous methods to work with strings that represent paths.
sFileName = Path.GetFileNameWithoutExtension(fupCtrl.PostedFile.FileName);
sFileName += "_" + nRandomNum.ToString();
sFileName += Path.GetExtension(fupCtrl.FileName);
fupCtrl.SaveAs(Path.Combine(dirPath, sFileName));
Try this, it can be work.
private const string ExcelUploadPath = "~//UploadedFiles//";
HttpPostedFile postedFile = context.Request.Files[FileObject];
string filename = Path.GetFileNameWithoutExtension(postedFile.FileName);
Related
Is there a simple or a more compact way to do this with a large number of files with one check-box (checked/unchecked), i have i think few thousand lines to put inside the code and i can sort them by year, or by type:
private void CheckBox()
{
try
{
switch (checkBox.IsChecked)
{
case true:
{
const string disable_picture100 = "images/disabled/picture100.png";
const string picture100 = "images\\disabled\\picture100.png";
Records[picture100].ReplaceContents(imagesPath, disable_picture100, content.FileRoot);
const string disable_picture101 = "images/disabled/picture101.png";
const string picture101 = "images\\disabled\\picture101.png";
Records[picture101].ReplaceContents(imagesPath, disable_picture101, content.FileRoot);
const string disable_picture102 = "images/disabled/picture102.png";
const string picture102 = "images\\disabled\\picture102.png";
Records[picture102].ReplaceContents(imagesPath, disable_picture102, content.FileRoot);
UpdateImage();
}
break;
case false:
{
const string enable_picture100 = "images/enabled/picture100.png";
const string picture100 = "images\\enabled\\picture100.png";
Records[picture100].ReplaceContents(imagesPath, enable_picture100, content.FileRoot);
const string enable_picture101 = "images/enabled/picture101.png";
const string picture101 = "images\\enabled\\picture101.png";
Records[picture101].ReplaceContents(imagesPath, enable_picture101, content.FileRoot);
const string enable_picture102 = "images/enabled/picture102.png";
const string picture102 = "images\\enabled\\picture102.png";
Records[picture102].ReplaceContents(imagesPath, enable_picture102, content.FileRoot);
UpdateImage();
}
break;
}
}
catch (Exception ex)
{
//ignored
}
}
Thank you!
List<string> fileNames = new List<string>(); //suppose you have names of files in a list
foreach(var name in fileNames)
{
if(checkBox.IsChecked)
{
Records[name].ReplaceContents
("images/disabled/" + name, "images\\disabled\\" + name, content.FileRoot);
}
else
{
Records[name].ReplaceContents
("images/enabled/" + name, "images\\enabled\\" + name, content.FileRoot);
}
}
Using the code below you can specify a directory (where the string says "FilePath". It gets all files with the extension .png
Then it checks once if the checkbox is checked or not.
And then loops over all the files in the enumerator
var allPngFilesInGivenDirectory = Directory.EnumerateFiles("FilePath").Where(x => x.ToLower().EndsWith(".png"));
var fileEnumerable = allPngFilesInGivenDirectory.GetEnumerator();
string partialPath = checkBox.IsChecked ? "enabled" : "disabled";
while (fileEnumerable.MoveNext())
{
string file = Path.GetFileName(fileEnumerable.Current);
string disable_picture = "images/" + partialPath + "/" + file;
string picture = "images\\" + partialPath + "\\" + file;
Records[picture].ReplaceContents(imagesPath, disable_picture, content.FileRoot);
UpdateImage();
}
Is this roughly what you are looking for?
string pictureName;
string newPictureName;
List<string> fileNames = new List<string>();
foreach(var name in fileNames)
{
if (checkBox.IsChecked)
{
pictureName = "images\\disabled\\" + name + ".png";
newPictureName = "images/disabled/" + name + ".png";
}
else
{
pictureName = "images\\enabled\\" + name + ".png";
newPictureName = "images/enabled/" + name + ".png";
}
}
Records[pictureName].ReplaceContents(imagesPath, newPictureName, content.FileRoot);
Let me know if not.
I have used the following code and it works fine. But sometimes it throws an exception:
Message :- The process cannot access the file 'DownloadDB\client\user\filename.db' because it is being used by another process.
Stack Trace :-
at System.IO.File.InternalDelete(String path, Boolean checkHost)
at System.IO.File.Delete(String path)
at Ionic.Zip.ZipEntry.InternalExtract(String baseDir, Stream outstream, String password)
at Ionic.Zip.ZipEntry.Extract(String baseDirectory)
at Ionic.Zip.ZipFile._InternalExtractAll(String path, Boolean overrideExtractExistingProperty)
at Ionic.Zip.ZipFile.ExtractAll(String path, ExtractExistingFileAction extractExistingFile)
at ecpMobileToWebSync.UnZipFiles(String strZipFilePath, String CombinePath, String fk_EmpGLCode)
My code is given below:
private string SyncDB(string FileArray)
{
string pathNew = "";
byte[] encodedDataAsBytesSyncDB = System.Convert.FromBase64String(FileArray);
pathNew = Server.MapPath("~/SyncDB/" + strClientName_File + "/" + UserName + "/" + Filename);
File.WriteAllBytes(pathNew, encodedDataAsBytesSyncDB);
byte[] encodedDataAsBytesDownloadDB = System.Convert.FromBase64String(FileArray);
pathNew = Server.MapPath("~/DownloadDB/" + strClientName_File + "/" + UserName + "/" + Filename);
File.WriteAllBytes(pathNew, encodedDataAsBytesDownloadDB);
encodedDataAsBytesSyncDB = null;
encodedDataAsBytesDownloadDB = null;
FileArray = null;
string strFileName = string.Empty;
if (File.Exists(pathNew))
{
strFileName = UnZipFiles(pathNew, Server.MapPath("~/DownloadDB/" + strClientName_File + "/" + UserName + "/"));
}
}
private string UnZipFiles(string strZipFilePath, string CombinePath)
{
string strZilEntryFileName = string.Empty;
ReturnData objReturnData = new ReturnData();
objReturnData.isValid = true;
objReturnData.Message = "";
try
{
using (ZipFile zip1 = ZipFile.Read(strZipFilePath))
{
strZilEntryFileName = zip1.Entries.Single().FileName;
var flattenFoldersOnExtract = zip1.FlattenFoldersOnExtract;
zip1.FlattenFoldersOnExtract = true;
zip1.ExtractAll(CombinePath, ExtractExistingFileAction.OverwriteSilently);
zip1.FlattenFoldersOnExtract = flattenFoldersOnExtract;
}
}
catch (Exception ex)
{
ErrorLogDetails.LogException(this.GetType().Name.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name.ToString());
objReturnData.isValid = false;
objReturnData.Message = MsgException_Failure;
}
return strZilEntryFileName;
}
In this code I am getting a byte array of a zip file from a client and then I am performing reverse engineering for converting the byte array to the zip file and then extracting it.
First I will call the SyncDB function with the byte array and then calling UnZipFiles for unzip the file.
It's all working fine but in some cases it will give an exception.
Strange, I can't get ASP.Net project (using C# mode) to log result into my D:\Web.log file and also no exception was thrown.
Is there something wrong with my simple code?
private static XmlDocument _doc = new XmlDocument();
private static string LogFileName = "D:\\Web.log";
static void LogToFile(string WebAddress, string IPAddress, string Title)
{
if (File.Exists(#"" + LogFileName + ""))
_doc.Load(#"" + LogFileName + "");
else
{
var root = _doc.CreateElement("Web");
_doc.AppendChild(root);
}
try
{
var el = (XmlElement)_doc.DocumentElement.AppendChild(_doc.CreateElement("Web"));
el.SetAttribute("Title", Title);
el.AppendChild(_doc.CreateElement("WebAddress")).InnerText = WebAddress;
el.AppendChild(_doc.CreateElement("IPAddress")).InnerText = IPAddress;
_doc.Save(#"" + LogFileName + "");
}
catch (Exception ex)
{
}
}
By removing the file D:\Web.log that I created, it is now able to append the file.
Remove the #"" and leading "" from all instances of #"" + LogFileName + "".
They are not needed as you have already escaped the variable LogFileName.
I have get my website path using HttpRuntime.AppDomainAppPath (like this C:/personal/Website/page.aspx)
Web service is always located on page.aspx parent of parent folder (like this C:/personal/Service/service.asmx ). I get the webservice-path using a ABC.dll in servicePath variable like this string servicePath="C:/personal/Service/service.asmx".
How to check service path against website path?
If (GetWebPath()== GetServicePath())
{
// ... do something
}
private string GetWebPath()
{
string path = HttpRuntime.AppDomainAppPath;
string[] array = path.Split('\\');
string removeString = "";
for(int i = array.Length; --i >= 0; )
{
removeString = array[array.Length - 2];
break;
}
path = path.Replace(#"\" + removeString + #"\", "");
return path;
}
private string GetServicePath()
{
string path = #"C:\MNJ\OLK\ABC.asmx"
string[] array = path.Split('\\');
string removeString = "";
for(int i = array.Length; --i >= 0; )
{
removeString = #"\" + array[array.Length - 2] + #"\" + array[array.Length - 1];
path = path.Replace(removeString, "");
break;
}
return path;
}
string webPath = #"C:\blabla\CS_Web\website\";
string servicePath = #"C:\blabla\CS_Web\SPM\Server.asmx";
if(Path.GetDirectory(Path.GetDirectoryName(servicePath))==Path.GetDirectoryName(webPath)
{
//You do something here
}
You have to up page to parent folder using Path.GetDirectoryName()
Try this:
System.Web.Server.MapPath(webPath);
This will return the physical file path of the currently executing web file.
More information can be found here: System.Web.Server
Providing you want to check the following pathes:
string webPath = #"C:\blabla\CS_Web\website\";
string servicePath = #"C:\blabla\CS_Web\SPM\Server.asmx";
you should call
string webPathParentDir = GetParentDirectoryName(webPath);
string servicePathParentDir = GetParentDirectoryName(servicePath);
if (servicePathParentDir.Equals(webPathParentDir, StringComparison.OrdinalIgnoreCase))
{
// ... do something
}
with method:
private string GetParentDirectoryName(string path)
{
string pathDirectory = Path.GetDirectoryName(servicePath);
return new DirectoryInfo(pathDirectory).Parent.FullName;
}
I have this method for grabbing the file name from a string URI. What can I do to make it more robust?
private string GetFileName(string hrefLink)
{
string[] parts = hrefLink.Split('/');
string fileName = "";
if (parts.Length > 0)
fileName = parts[parts.Length - 1];
else
fileName = hrefLink;
return fileName;
}
You can just make a System.Uri object, and use IsFile to verify it's a file, then Uri.LocalPath to extract the filename.
This is much safer, as it provides you a means to check the validity of the URI as well.
Edit in response to comment:
To get just the full filename, I'd use:
Uri uri = new Uri(hreflink);
if (uri.IsFile) {
string filename = System.IO.Path.GetFileName(uri.LocalPath);
}
This does all of the error checking for you, and is platform-neutral. All of the special cases get handled for you quickly and easily.
Uri.IsFile doesn't work with http urls. It only works for "file://".
From MSDN : "The IsFile property is true when the Scheme property equals UriSchemeFile."
So you can't depend on that.
Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.LocalPath);
Most other answers are either incomplete or don't deal with stuff coming after the path (query string/hash).
readonly static Uri SomeBaseUri = new Uri("http://canbeanything");
static string GetFileNameFromUrl(string url)
{
Uri uri;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
uri = new Uri(SomeBaseUri, url);
return Path.GetFileName(uri.LocalPath);
}
Test results:
GetFileNameFromUrl(""); // ""
GetFileNameFromUrl("test"); // "test"
GetFileNameFromUrl("test.xml"); // "test.xml"
GetFileNameFromUrl("/test.xml"); // "test.xml"
GetFileNameFromUrl("/test.xml?q=1"); // "test.xml"
GetFileNameFromUrl("/test.xml?q=1&x=3"); // "test.xml"
GetFileNameFromUrl("test.xml?q=1&x=3"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/test.xml?q=1&x=3"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/test.xml?q=1&x=3#aidjsf"); // "test.xml"
GetFileNameFromUrl("http://www.a.com/a/b/c/d"); // "d"
GetFileNameFromUrl("http://www.a.com/a/b/c/d/e/"); // ""
The accepted answer is problematic for http urls. Moreover Uri.LocalPath does Windows specific conversions, and as someone pointed out leaves query strings in there. A better way is to use Uri.AbsolutePath
The correct way to do this for http urls is:
Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.AbsolutePath);
I think this will do what you need:
var uri = new Uri(hreflink);
var filename = uri.Segments.Last();
using System.IO;
private String GetFileName(String hrefLink)
{
return Path.GetFileName(hrefLink.Replace("/", "\\"));
}
THis assumes, of course, that you've parsed out the file name.
EDIT #2:
using System.IO;
private String GetFileName(String hrefLink)
{
return Path.GetFileName(Uri.UnescapeDataString(hrefLink).Replace("/", "\\"));
}
This should handle spaces and the like in the file name.
As of 2020, handles query strings & encoded URLs
public static string GetFileNameFromUrl (string url)
{
var decoded = HttpUtility.UrlDecode(url);
if (decoded.IndexOf("?") is {} queryIndex && queryIndex != -1)
{
decoded = decoded.Substring(0, queryIndex);
}
return Path.GetFileName(decoded);
}
this is my sample you can use:
public static string GetFileNameValidChar(string fileName)
{
foreach (var item in System.IO.Path.GetInvalidFileNameChars())
{
fileName = fileName.Replace(item.ToString(), "");
}
return fileName;
}
public static string GetFileNameFromUrl(string url)
{
string fileName = "";
if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
{
fileName = GetFileNameValidChar(Path.GetFileName(uri.AbsolutePath));
}
string ext = "";
if (!string.IsNullOrEmpty(fileName))
{
ext = Path.GetExtension(fileName);
if (string.IsNullOrEmpty(ext))
ext = ".html";
else
ext = "";
return GetFileNameValidChar(fileName + ext);
}
fileName = Path.GetFileName(url);
if (string.IsNullOrEmpty(fileName))
{
fileName = "noName";
}
ext = Path.GetExtension(fileName);
if (string.IsNullOrEmpty(ext))
ext = ".html";
else
ext = "";
fileName = fileName + ext;
if (!fileName.StartsWith("?"))
fileName = fileName.Split('?').FirstOrDefault();
fileName = fileName.Split('&').LastOrDefault().Split('=').LastOrDefault();
return GetFileNameValidChar(fileName);
}
Usage:
var fileName = GetFileNameFromUrl("http://cdn.p30download.com/?b=p30dl-software&f=Mozilla.Firefox.v58.0.x86_p30download.com.zip");
Simple and straight forward:
Uri uri = new Uri(documentAttachment.DocumentAttachment.PreSignedUrl);
fileName = Path.GetFileName(uri.LocalPath);
//First Method to get fileName from fileurl
List<string> fileNameListValues = new List<string>();
//fileNameListValues List consist of fileName and fileUrl
//we need to get fileName and fileurl from fileNameListValues List
name
foreach(var items in fileNameListValues)
{
var fileUrl = items;
var uriPath = new Uri(items).LocalPath;
var fileName = Path.GetFileName(uriPath);
}
//Second Way to get filename from fileurl is ->
fileNameValue = "https://projectname.com/assets\UploadDocuments\documentFile_637897408013343662.jpg";
fileName = " documentFile_637897408013343662.jpg";
//way to get filename from fileurl
string filename =
fileNameValue.Substring(fileNameValue.LastIndexOf("\\") + 1);