Visual Studio 2010 working directory - c#

I'm developing a C# asp.net web application. I'm basically done with it, but I have this little problem. I want to save xml files to the "Users" folder within my project, but if I don't psychically hard code the path "C:......\Users" in my project it wants to save the file in this "C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\Users" folder, this is an annoying problem because I can't use the hard coded directory on our web hosts server. Also, I have a checkbox list that populates from the the "DownloadLibrary" folder in my project, and its suppose to download the files from that fold but its also looking to the "C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\" folder for download even though its populating from the correct folder. I'm very confused by this, its the first time something like this has ever happened to me. Can anyone please help me with this, its the only thing standing in my way to complete this project.

You don't want to use the working directory at all; you want to use a directory relative to where the web application is located (which can be retrieved from HttpRequest.ApplicationPath.
HttpRequest request = HttpContext.Current.Request;
// get the physical path to the web application
string pathToApp = request.MapPath(request.ApplicationPath);
string usersPath = System.IO.Path.Combine(pathToApp, "Users");
Update
As VincayC points out; asp.net development is not my strongest skill ;) The above code is essentially equivalent of this (much simpler) code:
string usersPath = HttpRequest.Current.Request.MapPath("~/Users");
If this code appears in the code-behind of a page, you can probably cut HttpContext.Current as well, since the page has a Request property.

That did fix the one problem I'm having, but the downloads are still not downloading from the right place, the program still wants to get the files from "C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\" directory here is the code I'm using
--Code to populate the checkbox--
HttpRequest request = HttpContext.Current.Request;
// get the physical path to the web application
string appPath = request.MapPath(request.ApplicationPath);
string directory = System.IO.Path.Combine(appPath, "DownloadLibrary/");
// Get the list of files into the CheckBoxList
var dirInfo = new DirectoryInfo(directory);
cblFiles.DataSource = dirInfo.GetFiles();
cblFiles.DataBind();
--Download Button Code--
// Tell the browser we're sending a ZIP file!
var downloadFileName = string.Format("Items-{0}.zip", DateTime.Now.ToString("yyyy-MM-dd-HH_mm_ss"));
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", "filename=" + downloadFileName);
// Zip the contents of the selected files
using (var zip = new ZipFile())
{
// Add the password protection, if specified
/*if (!string.IsNullOrEmpty(txtZIPPassword.Text))
{
zip.Password = txtZIPPassword.Text;
// 'This encryption is weak! Please see http://cheeso.members.winisp.net/DotNetZipHelp/html/24077057-63cb-ac7e-6be5-697fe9ce37d6.htm for more details
zip.Encryption = EncryptionAlgorithm.WinZipAes128;
}*/
// Construct the contents of the README.txt file that will be included in this ZIP
var readMeMessage = string.Format("Your ZIP file {0} contains the following files:{1}{1}", downloadFileName, Environment.NewLine);
// Add the checked files to the ZIP
foreach (ListItem li in cblFiles.Items)
if (li.Selected)
{
// Record the file that was included in readMeMessage
readMeMessage += string.Concat("\t* ", li.Text, Environment.NewLine);
// Now add the file to the ZIP (use a value of "" as the second parameter to put the files in the "root" folder)
zip.AddFile(li.Value, "Your Files");
}
// Add the README.txt file to the ZIP
//zip.AddEntry("README.txt", readMeMessage, Encoding.ASCII);
// Send the contents of the ZIP back to the output stream
zip.Save(Response.OutputStream);</pre></code>
I'm not sure how to get the downloads to point to my application directory,I tried everything I can think off.

Related

How to Get current date and create directory Everyday in C#?

get current date and make directory and second when directory is created, in that directory I have to store excel file and also save file as current date.
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists("C:\\Users\\Krupal\\Desktop\\" + Todaysdate))
{
Directory.CreateDirectory("C:\\Users\\Krupal\\Desktop\\" + Todaysdate);
}
This code have made directory with current date.
But when I want to store file in that directory, it generates the error:
Could not find a part of the path
'D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
Belove path is store excel file that i have to store.
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Actually you are making the directory in a path then you are saving the .xls in another path.
You are making the directory using this path:
"C:\\Users\\Krupal\\Desktop\\" + Todaysdate
Then, here the path where you are trying to save the .xls:
Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"
The error shows the problem clearly, it could not fin this path:
D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
While creating the .xls you are omitting the root path, so the process looks for the path 22-01-2020\22-01-2020.XLS in his working directory D:\WORK\RNSB\RNSB\bin\Debug.
You just need to align those paths: I sugget you to use relative paths, so here how you should fix your code:
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists(Todaysdate))
{
Directory.CreateDirectory(Todaysdate);
}
//then
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
I presume you are running your WinForms application in Debug mode. This means that your current path is [your application path]\bin\Debug. If you look in file explorer, you will find that an executable has been created there. When using StreamWriter without an absolute file name, the file it tries to create is relative to the current execution path (in your case 'D:\WORK\RNSB\RNSB\bin\Debug'). StreamWriter will create a new file, if one does not exist, but it will not create a new folder, and you are passing it Todaysdate + "\\" which is effectively a new folder. Hence you are getting the error message.
To fix your problem, you need to provide the absolute path to your newly created directory thus:
using (System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\Krupal\\Desktop\\" + Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Winforms always expect directories inside Debug Folder, since it's EXE file is inside Debug and try to find it inside Debug folder.
In error it clearly shows that it is looking inside "Debug" folder.
Can you check whether File Exists in the mentioned folder created by you in C Drive.
// To Write File
System.IO.File.WriteAllLines(#"C:\Users\Public\TestFolder\WriteLines.txt", lines);
You can follow this MSDN Post, hope it helps, if Yes, please Upvote it
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file

Windows Forms app on shared location, save file locally

My problem is that I have a windows forms application which is located on a shared location, which is doing some logic and at the end i need to export the data into an excel file.
But the excel file should be exported to the machine that the users is logged in, not on the shared server where the application is hosted ...
Any Ideas?
Example of the situation:
The location of the application is at 192.168.1.150\AppName\App.exe
I have access to this shared location and I'm starting the exe file from there.
I need the application to export an excel file to my computer on my desktop .... how?
If you think the folder "My Documents" is a good place to save the Excel file, then this code will help to get you the path:
var folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
or if you want to put the file on the Desktop:
var folderPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
The code works regardless of where the folder "My Documents" (or "Desktop") is located for the user (C:, D:, Network share, etc), or which language version his windows installation is using.
To combine with a time based file name:
var fileName = $"your_file_{DateTime.Now:yyMMddHHmmss}.xlsx";
var fullPath = Path.Combine(folderPath, fileName);
I often use time based file names to not overwrite if there is a previous file. (It would of course overwrite if created the same second)
If you want a file name that is guaranteed to be unique you can use a Guid instead of DateTime:
var fileName = $"your_file_{Guid.NewGuid():N}.xlsx";
If the file is just used "within the program" you can also store it in the temporary files folder. To get the path to the temporary files folder you write var folderPath = Path.GetTempPath()
Hope this helps!
Why don't you just use Save File Dialog and save the excel file where you want? Something like this:
private void SaveFile_FileOk(object sender, CancelEventArgs e)
{
string name = SaveFile.FileName;
string[] savearray = new string[] { "some test:" }
File.WriteAllLines(name, savearray);
//this is just an example, your excel file goes here.
}
And on your button to save:
SaveFile.ShowDialog();
You can choose the path for where you want to save...

Not allowed to load local resource from App_Data folder

I need to server a larger amount of Pdf's which require authorisation in order to be able to download.
I have read that it is advisable to place them in the App_Data folder.
I have created three folders in the App_Data folder:
> SetOne
> SetTwo
> SetThree
I need to pass these files to my view.
Controller
var files = Directory.EnumerateFiles(Server.MapPath("~/App_Data/SetOne"));
return View(files);
View
<ul>
#foreach (var fullPath in Model)
{
var fileName = Path.GetFileName(fullPath);
var downloadPath = #Path.GetDirectoryName(fullPath) + "\\" + #fileName;
<li>#fileName</li>
}
</ul>
Using the above code, I am able to list the contents of the SetOne folder in an unordered list, however when I attempt to view one of the Pdf's I see:
Not allowed to load local resource:
file:///B:/Development/MyProject/MyProject.Web/App_Data/SetOne/sampleOne.pdf
How can I allow the application to give access to these files?
edit
I've also tried creating a new folder called Pdfs and moving the documents to this, however I get the same error message when I view in chrome dev tools.
Do I need to implement a Http Handler for this task?
Your approach is OK for WinForms application but shouldn't work for Web. downloadPath should contain the Url but not the physical path on the file (like some.com/pdfs/1.pdf)
You could use Server.MapPath for this case

how to Save File using C# Windows Application

I'm using C# windows application .
I want to save files in my local system.
I used Open File dialog to attach the files.
Here the text inside the file is copying,I want the file itself to get copied with a new name.But what I am really looking for is , it should just save the file automatically and not show the SaveDialog Box?
How it can be done in windows application.Can anybody help me please?
The code is shown below:
private string GetFileName()
{
OpenFileDialog op1 = new OpenFileDialog();
DialogResult result = op1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
txtEn.Text = op1.FileName;
FileName = op1.FileName;
//MessageBox.Show(FileName);
File.Copy(op1.FileName, #"D:\Backup\");
}
return FileName;
}
SQL Server 2012 seems unrelated to your question. Provided that you have proper access rights to the target directory, then in order to automate the procedure (as per your question) you don't need to use the OpenFileDialog; just a single line should suffice the goal:
//Overwriting a file of the same name is not allowed
File.Copy(FileName, #"D:\Backup\" + FileName)
or
//Overwriting a file of the same name is allowed
File.Copy(FileName, #"D:\Backup\" + FileName, true)
You can also apply some additional logic pertinent to backup file naming (upon necessity).
Hope this may help. Best regards,
Are you trying to copy a file from some x location on your file system to y location (in your case D:\Backup folder) in the file system? If that is the requirement here, I see that you are using the FileName property of OpenFileDialog which gets the File path. This you are appending to D:\Backup. You should instead use the Path.GetFileName property to first extract the file name with extension and then append it to the new folder path
File.Copy(fileName, #"D:\Backup\" + Path.GetFileName(fileName));

Multiple upload files from file list in User computer to server in ASP.Net

pe someone can help me on this.
I've been googling & searching a lot regarding this issue.
I'm working on web application where I need to :
Click a button to get a folder/directory of files - Done with
javascript
Get list of available files is the selected folder/directory - Done
with javascript
Start uploading those file in the list into server folder - Failed!
As I understand my limitation so far :
I cannot programmatically assign a value to asp:FileUpload control -
readOnly
I cannot access those file in the list in FileInfo/FileStream - it's fail as it can't find the source file given from the list due to it's not
came from server directory
came from server directory
I cannot simply try to use File.Copy to upload the file - it's fail as it can't find the source file given from the list due to it's not
came from server directory
I've been getting error :
"Could not find a part of the path"
List of files in the folder, example :
File1.pdf
File2.png
File3.txt
File4.xls
File5.jpg
While in the server, I already create a folder named as "Temp" but the problem actually because system can't recognize the path of those file in the list.
This is part of my code :
string strPath = #"C:\Users\Administrator\Desktop\Sample";
string strListedFiles = txtList.InnerText.ToString();
string[] strFiles = strListedFiles.split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach(string strFile in strFiles)
{
FileInfo fiFile = new FileInfo(strPath.ToString() + "\\" + strFile.Trim());
FileStream fsFile = fiFile.OpenRead(); //Failed at here
...
...
...
...
}
Perhaps you are looking for something which has been shown with demo in this tutorial.
This will allow you to upload multiple files concurrently.
Another alternative example with jQuery MultiFile is given here.

Categories

Resources