Download File from DataTable - c#

I'm trying to develop some kind of FTP program in school. The service they provided me to download files from their server only downloads one file at a time and if I try to download a folder it returns a blank file. How is it possible to create some kind of system to download the whole directory (even the files inside the directory of the selected directory)?
This is what I use to get the files:
foreach (ListViewItem cadaItem in listView2.SelectedItems)
{
string type = listView2.SelectedItems[0].SubItems[2].Text;
MessageBox.Show(type);
byte[] fileBytes = new byte[666666];
byte[] hash = new byte[666666];
if (type != "")
{
servDin.GetFileMD5Async("", "", Vars.pastaLocal + #"\" + cadaItem.Text, hash, fileBytes);
using (Stream file = File.OpenWrite(Vars.pastaLocal + #"\" + Convert.ToString(cadaItem.Text)))
{
file.Write(fileBytes, 0, fileBytes.Length);
}
}
I wanted to use a datatable to get the filenames and download the files from there. is it possible?
Thank You

Related

Blazor Server-Side download issues in IIS

I am trying to download a List of files (user has the option to select multiple). My current code below works fine in localhost (writing and opening the downloads folder). However, when I upload to IIS it gives an error saying that the system configuration is not found.
Please see below:
if (SelectDownloadFiles.Count > 0)
{
//Downloads folder (User profile)
string DownloadFolder = Environment.ExpandEnvironmentVariables("%userprofile%/downloads/");
//This is a little hack to get the literal path for the Downloads folder without too much of back-and-forth and ellaboration
string FolderForward = DownloadFolder.Replace(#"/", #"\");
string Folder = FolderForward.Replace(#"\\", #"\");
foreach (var items in SelectDownloadFiles)
{
//Get Date
var GetDate = items.Substring(0, 6);
//Add 2 days to be consistent to what is displayed to the user (when files were generated)
var FileDate = DateTime.ParseExact(GetDate, "yyMMdd", CultureInfo.InvariantCulture).AddDays(2);
//Get Files
string Pathname = #"D:\";
string FullPathName = Path.Combine(Pathname, items);
byte[] FileBytes = System.IO.File.ReadAllBytes(FullPathName);
MemoryStream Ms = new MemoryStream(FileBytes);
//Rename the file to become user friendly
string DownloadPath = Path.Combine(DownloadFolder, "My Files " + FileDate.ToString("MM-dd-yyyy") + ".zip");
//Write file(s) to folder
FileStream File = new FileStream(DownloadPath, FileMode.Create, FileAccess.Write);
Ms.WriteTo(File);
File.Close();
Ms.Close();
}
//Open Downloads Folder with files
Process.Start("explorer.exe", Folder);
navigationManager.NavigateTo("/default", true);
//DisplayMessage.Show("File(s) successfully downloaded. Please check your “Downloads” folder to access your file(s).", "OK", "check");
}
else
{
Toaster.Add("Please select at least one file to download.", MatToastType.Warning);
}
I've also tried to use the solution below to no avail:
private readonly IWebHostEnvironment _webHostEnvironment;
public YourController (IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment= webHostEnvironment;
}
If I use the "folderoptionpath" and choose "MyDocuments" for instance, the files download to the root path of the files inside IIS.
Is there anything else I need to be doing to get to this to work?
Thanks in advance!
Well, after spending some time researching this, I was finally able to get it going. I ended up using a Nuget Package called BlazorFileSaver and it works just fine. Here's the repo: https://github.com/IvanJosipovic/BlazorFileSaver/blob/master/src/BlazorFileSaver.Sample/Pages/Index.razor
I hope this can help someone else in the future.

how to save a file in the directory you are currently in (COSMOS)

So I'm making a Cosmos OS and I am having some trouble. I have this code that makes a file. what it does is it asks What is the name of the file and extension then what is the files contents then makes the file. The Problem is is that it only saves to main directory of 0:\ and doesn't work when you make a file while in a directory like 0:\TEST. This is the code I have for the file creator. I want to know if it's possible to make it save the file to the directory you are currently in.
Console.Write("File Name (put in the extension name):");
var finput = Console.ReadLine().ToLower();
string fileName = finput;
// Check if file already exists. If yes, delete it.
if (File.Exists(fileName))
{
File.Delete(fileName);
}
Console.Write("File Contents:\n");
var text = Console.ReadLine().ToLower();
using (FileStream fs = File.Create(fileName))
{
// Add some text to file
Byte[] title = new UTF8Encoding(true).GetBytes(text);
fs.Write(title, 0, title.Length);
}
Console.WriteLine("File Made!");
This may be a late answer, but try this:
var dir = Directory.GetCurrentDirectory;
var file = (filename);
File.Create(dir + "\\" + file);
I haven't checked this code but it should be something like this. This (should) do the same as your code above.

DotNetZip uncompressed exe files not opening

I'v been using the DotNetZip library for uncompressing some files from a ZIP file, compressed using the same library. That ZIP file contains exe files, but once decompressed, some of the exe file decompressed is not opening anymore. That problem is not happening if i decompress the file manually with WinRAR.
The code i'm using is this one...
if (!System.IO.File.Exists("ApplicationSample.zip")) { MessageBox.Show("No data found", "Warning"); return false; }
var Archive = ZipFile.Open(DatFilePath, ZipArchiveMode.Read);
var InstallPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + #"/ApplicationSample";
if (Directory.Exists(InstallPath))
Directory.Delete(InstallPath, true);
Directory.CreateDirectory(InstallPath);
Archive.ExtractToDirectory(InstallPath);
var ArchiveEd = new Ionic.Zip.ZipFile("ApplicationSample.zip");
ArchiveEd.UseUnicodeAsNecessary = true;
ArchiveEd.ZipError += ApplicationSample_ZipError;
ArchiveEd.ExtractAll(InstallPath);
ArchiveEd.Dispose();
ShellLink link = new ShellLink();
link.WorkingDirectory = InstallPath;
link.Target = InstallPath + "/ApplicationSample.exe";
link.IconPath = InstallPath + "/ApplicationSample.ico";
link.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/ApplicationSample.lnk");
The exe file i'm trying to open is an WPF application that works correctly if i do the same operation manually.
I don't know what's happening here and i would like to know what's the problem.
Thanks!!

Create an Excel file on server and send to a browser

I'm using EPPlus to create an excel file on the server. The problem is that I wan't the file to be saved on the clients harddrive and when I the application up on a server I believe this will save the file on the server harddrive.
Is it possible to send this file back to the client/browser some how?
public void CreateAnnuityExcelSheet(List<Calculation> cList, FormCollection form, int DTCyear)
{
List<Calculation> newList = new List<Calculation>();
newList.Add(cList.First()); //Getting the values for the first row
var StartValue = newList[0].StartValue;
var radio = form["advanceOrArrears"];
string fileName = newList[0].CalculationName;
string path = #"C:\ExcelFiles\" + fileName + ".xlsx"; //Path for the file
FileInfo info = new FileInfo(path);
info.Directory.Create(); //If C:\ExcelFiles does not exist, create it
if (!info.Exists)
{
using (ExcelPackage package = new ExcelPackage(info))
{
ExcelWorksheet ws = package.Workbook.Worksheets.Add(fileName);
//Styles for the sheet
package.Save();
}
}
}
The easiest way would be to send the bytes as File to browser. If your library for creating Excel files allows you to save to stream (like for example ClosedXML does) then you can do in your MVC action
var stream = new MemoryStream();
workbook.SaveAs(stream);
stream.Position = 0;
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", "file.xlsx");
If you can't save it to memory stream then save it to server's disc and then you can just pass file path and content type to return File().
I've used a httphandler for sending the byte file object to the browser.
This link should help, Generating a file, then launching a secure download
So save the file on the server then transmit it to the user in your controller:
return new FilePathResult(myFilePath,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

Append to file failure when executable not in same folder as data files

Problem is now solved. Mistake by me that I hadn't seen before.
I am pretty new to coding in general and am very new to C# so I am probably missing something simple. I wrote a program to pull data from a login website and save that data to files on the local hard drive. The data is power and energy data for solar modules and each module has its own file. On my main workstation I am running Windows Vista and the program works just fine. When I run the program on the machine running Server 2003, instead of the new data being appended to the files, it just overwrites the data originally in the file.
The data I am downloading is csv format text over a span of 7 days at a time. I run the program once a day to pull the new day's data and append it to the local file. Every time I run the program, the local file is a copy of the newly downloaded data with none of the old data. Since the data on the web site is only updated once a day, I have been testing by removing the last day's data in the local file and/or the first day's data in the local file. Any time I change the file and run the program, the file contains the downloaded data and nothing else.
I just tried something new to test why it wasn't working and think I have found the source of the error. When I ran on my local machine, the "filePath" variable was set to "". On the server and now on my local machine I have changed the "filePath" to #"C:\Solar Yard Data\" and on both machines it catches the file not found exception and creates a new file in the same directory which overwrites the original. Anyone have an idea as to why this happens?
The code is the section that download's each data set and appends any new data to the local file.
int i = 0;
string filePath = "C:/Solar Yard Data/";
string[] filenamesPower = new string[]
{
"inverter121201321745_power",
"inverter121201325108_power",
"inverter121201326383_power",
"inverter121201326218_power",
"inverter121201323111_power",
"inverter121201324916_power",
"inverter121201326328_power",
"inverter121201326031_power",
"inverter121201325003_power",
"inverter121201326714_power",
"inverter121201326351_power",
"inverter121201323205_power",
"inverter121201325349_power",
"inverter121201324856_power",
"inverter121201325047_power",
"inverter121201324954_power",
};
// download and save every module's power data
foreach (string url in modulesPower)
{
// create web request and download data
HttpWebRequest req_csv = (HttpWebRequest)HttpWebRequest.Create(String.Format(url, auth_token));
req_csv.CookieContainer = cookie_container;
HttpWebResponse res_csv = (HttpWebResponse)req_csv.GetResponse();
// save the data to files
using (StreamReader sr = new StreamReader(res_csv.GetResponseStream()))
{
string response = sr.ReadToEnd();
string fileName = filenamesPower[i] + ".csv";
// save the new data to file
try
{
int startIndex = 0; // start index for substring to append to file
int searchResultIndex = 0; // index returned when searching downloaded data for last entry of data on file
string lastEntry; // will hold the last entry in the current data
//open existing file and find last entry
using (StreamReader sr2 = new StreamReader(fileName))
{
//get last line of existing data
string fileContents = sr2.ReadToEnd();
string nl = System.Environment.NewLine; // newline string
int nllen = nl.Length; // length of a newline
if (fileContents.LastIndexOf(nl) == fileContents.Length - nllen)
{
lastEntry = fileContents.Substring(0, fileContents.Length - nllen).Substring(fileContents.Substring(0, fileContents.Length - nllen).LastIndexOf(nl) + nllen);
}
else
{
lastEntry = fileContents.Substring(fileContents.LastIndexOf(nl) + 2);
}
// search the new data for the last existing line
searchResultIndex = response.LastIndexOf(lastEntry);
}
// if the downloaded data contains the last record on file, append the new data
if (searchResultIndex != -1)
{
startIndex = searchResultIndex + lastEntry.Length;
File.AppendAllText(filePath + fileName, response.Substring(startIndex+1));
}
// else append all the data
else
{
Console.WriteLine("The last entry of the existing data was not found\nin the downloaded data. Appending all data.");
File.AppendAllText(filePath + fileName, response.Substring(109)); // the 109 index removes the file header from the new data
}
}
// if there is no file for this module, create the first one
catch (FileNotFoundException e)
{
// write data to file
Console.WriteLine("File does not exist, creating new data file.");
File.WriteAllText(filePath + fileName, response);
//Debug.WriteLine(response);
}
}
Console.WriteLine("Power file " + (i + 1) + " finished.");
//Debug.WriteLine("File " + (i + 1) + " finished.");
i++;
}
Console.WriteLine("\nPower data finished!\n");
Couple of suggestions wich I think will probably resolve the issue
First change your filePath string
string filePath = #"C:\Solar Yard Data\";
create a string with the full path
String fullFilePath = filePath + fileName;
then check to see if it exists and create it if it doesnt
if (!File.Exists(fullFilePath ))
File.Create(fullFilePath );
put the full path to the file in your streamReader
using (StreamReader sr2 = new StreamReader(fullFilePath))

Categories