I'm Creating a web application using Visual Studio. in that I want to save pdf that are Uploaded, to a Specific Path. So I Used Following Code
String fileName = BalanceSheet.FileName;
String fName = "pdf / Accounts / BalanceSheet/ ";
String fname = Filename.Text;
String location = AppDomain.CurrentDomain.BaseDirectory + "/pdf/Accounts/BalanceSheet/";
String filePath = System.IO.Path.Combine(location,fileName);
BalanceSheet.SaveAs(MapPath(fName+fname));
here BalanceSheet is a FileUpload Control. when the Following Code get executed,BalanceSheet.SaveAs(MapPath(fName+fname)); it'Show an Exception Saying couldn't find Some parts of the Path.when I use BalanceSheet.SaveAs(MapPath(filePath));, it Shows an Exception Saying Expecting Virtual Path.
Control
try the below code:
BalanceSheet.SaveAs(Path.Combine(Server.MapPtah("~/"), fName + fname);
Related
It should not return the URL like http://something.azurewebsites.net/signup instead custom domain name space.
with JavaScript and C# as well.
able to see using developer options of the browser or using fiddler.
something like
HttpContext.Current.Request.Url.Scheme+"://"+HttpContext.Current.Request.Url.Host+"/SignUp/"
Using custom domain name getting current path name.
System.IO.Path.GetFullPath method to get the full path of the current executing assembly.
System.Reflection.Assembly.GetExecutingAssembly().Location -To get the location of the current executing assembly.
And combining the custom domain and the current path to get the complete path.
To fetch the path name for the domain space names with JavaScript you can use
window.location.hostname
'window.location.hostname` if you dont want the `port` (like `http://localhost:8080/`, `window.location.host = 'localhost:8080'` and `window.location.hostname = 'localhost`
string str = HttpContext.Current.Request.Url.PathAndQuery;
string strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(str, "/");
string customDomain = "https://www.something.com/";
string currentPath = System.IO.Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location);
string combinedPath = customDomain + currentPath;
Console.WriteLine("The combined pah is: " + combinedPath);
Reference taken from
MDN Web Docs
I want to save file to a specific location with some folder creation based on my requirement. So I wrote the below code.
public string CreateFilePath(string addedFolderName)
{
string folderPath = ConfigurationManager.AppSettings["DocDirectory"].ToString();
string FileUplPath = folderPath + "\\" + addedFolderName + "\\";
if (!Directory.Exists(FileUplPath))
{
Directory.CreateDirectory(FileUplPath);
}
flUploadDocs.SaveAs(FileUplPath + Path.GetFileName(flUploadDocs.FileName));
return folderPath;
}
But I am unable to get the filepath here. I am getting it as null
getting null at
Path.GetFileName(flUploadDocs.FileName)
<asp:FileUpload ID="flUploadDocs" runat="server" />
Please suggest what is wrong here.
Path.GetFileName() returns the file name and extension of the specified path string
if im correct this only fills in the file name and not the directory + name.
Path.GetFileName(flUploadDocs.FileName)
possible solution
Path.GetFileName(FileUplPath+flUploadDocs.FileName)
eventough im confused why you try to retrieve the path again after just having saved it?
The issue is that the webservice does not have the fileupload data. Here is the full code from our extended conversation:
[WebMethod]
public static string InsertUpdateMWSiteData(MWInsertUpdateFields MWInsertUpdateFields)
{
string strInsertUpdateMWInfo = "";
try
{
Dashboard dshb = new Dashboard();
dshb.CreateFilePath(MWInsertUpdateFields.SapID + "_" + MWInsertUpdateFields.CandidateID);
strInsertUpdateMWInfo = CommonDB.InsertUpdateMWSiteInfo(MWInsertUpdateFields);
}
catch (Exception)
{
throw;
}
return strInsertUpdateMWInfo;
}
public string CreateFilePath(string addedFolderName)
{
string folderPath = ConfigurationManager.AppSettings["DocDirectory"].ToString();
string FileUplPath = folderPath + "\\" + addedFolderName + "\\";
if (!Directory.Exists(FileUplPath))
{
Directory.CreateDirectory(FileUplPath);
}
if (flUploadDoc.HasFile == true)
{
string strFilename = Path.GetFileName(flUploadDoc.FileName);
flUploadDoc.SaveAs(FileUplPath + Path.GetFileName(flUploadDoc.PostedFile.FileName));
}
return folderPath;
}
The problem is that after uploading a file, a request is sent to a webmethod which is being hosted in another instance of the program. This Webmethod checks its own instance for the fileupload control and data, and doesn't find it because it is in a different instance. This is why your fileupload control is returning null even on a sanity check of .HasFile().
One solution is to pass the data to the Webservice. You could for example pass the data to your webmethod as a byte[], and then on the webservice side reconvert it back into its original file type. After completing this process, save the file to your local filesystem. To do this you may need to pass the extension type and file name.
You may also want to add some validation to limit the file types accepted to only the most common file types like images, .doc, .excel, and whatever you have the library to support the conversion of.
If you want to save files directly to your filesystem using the upload control, you can do so but you will have to exclude the webservice step.
Please also see the discussion in chat for details.
string UserFolder = Session["Username"].ToString();
if (!Directory.Exists("~/MisReports/EmailAttachment/"+UserFolder))
{
Directory.CreateDirectory("~/MisReports/EmailAttachment/"+UserFolder);
}
filePathE = Server.MapPath("~/MisReports/EmailAttachment/" + UserFolder + "/");
filePathE = filePathE + a + ".pdf";
bool isExist = File.Exists(filePathE);
if (isExist)
{
File.Delete(filePathE);
}
report.ExportToDisk(ExportFormatType.PortableDocFormat, filePathE);
I get the error
Could not find a part of the path
if (!Directory.Exists("~/MisReports/EmailAttachment/"+UserFolder))
{
Directory.CreateDirectory("~/MisReports/EmailAttachment/"+UserFolder);
}
in this area code does not enter if check although that the folder has not been created
The ~ is probably not evaluated if you are running on Windows. Windows is not Unix. Read up on Path.Combine, Environment.GetFolderPath and Environment.SpecialFolder on MSDN. You should build a path with code like
string directoryName = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "MisReports/EmailAttachment", UserFolder);
I m saving path of images, audio and video files that path is of folder saved at server. Now I want that path as link in c# for the purpose of download.
Is there any way how to do that?
I'm not suppose to use gridview to show link.
EDIT:-
ServerFileName = System.IO.Path.Combine(ServerSavePathI, ClientFileName);
string serverPath=Server.MapPath(ServerFileName);
FileUpload1.SaveAs(serverPath);
dbInsert("Image",fileName,fileExt,serverPath);
//dbinsert stores values to database. and in database it is showing path just as
//c:InetpubwwwRootFileUploadingpenguin.jpg and not showing
//'\\' though i have used datatype varchar
EDIT:-
protected void dbInsert(string fileType,string fileName,string fileExt,
string filePath)
{
string getSQL1;
getSQL1 = "INSERT into tbluploadedfilesdetail (FileDownloaded,FileType,
FileName,FileExt,FilePath) VALUES ('false','" + fileType + "','" +
fileName + "','" + fileExt + "','"+filePath+"');";
MySqlConnection objMyCon1 = new MySqlConnection(strProvider);
objMyCon1.Open();
MySqlCommand cmd1 = new MySqlCommand(getSQL1, objMyCon1);
cmd1.ExecuteNonQuery();
objMyCon1.Close();
dbLoad();
}
Normally if you have images in folder named images under root folder of your site and you save path for an image named image1.jpg as images/image1.jpg you can get link as follows:
var path="images/image1.jpg";//you get this from db
var link=Page.ResolveUrl("~/"+path);//gives /images/image1.jpg
~/ specified path relative to root folder of your site.
Normally I save the physical path and virtual path separately. Moreover you can get physical path from virtual path easily. You should save FileUpload/ingpenguin.jpg only and can get physical path easily as follows:
var root = Server.MapPath("/");//path to the root folder
// will return full path
var imagePath = Server.MapPath("FileUpload/inpenguin.jpg");
For more informaiton you can refer to 4guysfromrolla
How do I write the error faced into the log.txt?
Firstly, I get error file name from web config as follows:
string Errorlog = System.Configuration.ConfigurationManager.AppSettings["Errorlog.txt"];
Next, I try to get the full path of the text file; but i do not know which one will pull it out.
This is a few. I want to get the full path by not making it static.
//string path = Global.getLogFilePath();
//string path = Path.GetFileName(directoryFullPath);
//string path = openFileDialog.FileName;
//string path = Path.Combine(System.Environment.CurrentDirectory);
//string path = Path.GetFullPath("Errorlog.txt");
//string path = Directory.GetCurrentDirectory();
//string path = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName());
//string path = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
//string path = Environment.CurrentDirectory.ToString();
//string path = System.Environment.GetEnvironmentVariable("TEMP");
//if (!path.EndsWith("\\")) path += "\\";
Put log.txt in a Logs sub-folder of your web site and then you can get the absolute path like this:
string logFile = HttpContext.Current.Server.MapPath("~/Logs/log.txt");
Also don't forget to restrict the public access to the Logs folder to avoid anyone reading your application log files.