I am trying to download a list of files, but isn't really sure of how to proceed.
As the topic says, I am using DropNet, and this is the procedure I am trying to download the files with:
Get a list of all files in my applications dedicated folder and store them in a List as strings.
Then trying the following:
foreach (string file in files)
{
_client.GetFileAsync("/" +file,
(response) =>
{
using(FileStream fs = new FileStream(path +file +".gttmp", FileMode.Create))
{
for(int i = 0; i < response.RawBytes.Length; i++)
{
fs.WriteByte(response.RawBytes[i]);
}
fs.Seek(0, SeekOrigin.Begin);
for(int i = 0; i < response.RawBytes.Length; i++)
{
if(response.RawBytes[i] != fs.ReadByte())
{
MessageBox.Show("Error writing data for " +file);
return;
}
}
}
},
(error) =>
{
MessageBox.Show("Could not download file " +file, "Error!");
});
}
Unfortunately it doesn't seem to work at all.
Anyone using DropNet and could suggest me something that would work?
Used synronous method instead:
foreach (string file in files)
{
var fileBytes = _client.GetFile("/" + file);
using (FileStream fs = new FileStream(path +file + ".gttmp", FileMode.Create))
{
for (int i = 0; i < fileBytes.Length; i++)
{
fs.WriteByte(fileBytes[i]);
}
fs.Seek(0, SeekOrigin.Begin);
for (int i = 0; i < fileBytes.Length; i++)
{
if (fileBytes[i] != fs.ReadByte())
{
MessageBox.Show("Error writing data for " + file);
break;
}
}
}
}
Your code to download file asynchronously works fine, I tried in following way and it proceeds without error.
client.GetFileAsync("/novemberrain.mp3",
(response) =>
{
using (FileStream fs = new FileStream(#"D:\novemberrain.mp3", FileMode.Create))
{
for (int i = 0; i < response.RawBytes.Length; i++)
{
fs.WriteByte(response.RawBytes[i]);
}
}
MessageBox.Show("file downloaded");
},
(error) =>
{
MessageBox.Show("error downloading");
});
Related
I have a flat file with comma separated values which need to be transfer to a datatable and the values on the first line is header name, will be used as columns name of the datatable. But Before that, I need to check if all required header (Some Mandatory headers) are available in the flat file. Please help me to develop a C# code to put the header validation.
`.
.
.
/getting full file path of Uploaded file and read all text
System.IO.StreamReader file = new System.IO.StreamReader(#path);
string line;
while ((line = file.ReadLine()) != null)
{
string[] linetemp = line.Split(new char[] { ',' });
if(tblcsv.Rows.Count==0)
{
foreach (string ColName in linetemp)
{
tblcsv.Columns.Add(ColName); //Creating columns with available headers names
}
}
tblcsv.Rows.Add();
.
.
.
`//remaining code
For example
If the flat file will contain
datetime,status,Assignee,Reporter,Duration,Col1,Col2,Remarks
1504451523568,Inprogress,ABC,BCD,120,True,B,comments...
1504451523567,Completed,DFG,BCD,120,True,B,comments...
1504451523566,unassigned,VNB,BCD,160,,B,comments...
1504451523565,Inprogress,ERT,FGH,150,True,,comments...
and I need to check that only First line have all mandaory header(like- datetime,Status,Assignee and Duration).
I tired to implement your particular requirement with a sample Csv file from online. Csv file can be found here, I may not have a sophisticated code, but tried to take a simplest way to solve this particular problem.
Below is the short version of code which is of your importance.
String firstLine;
var fileStream = new FileStream( # "C:\Users\user\Desktop\AssetsImportCompleteSample.csv", FileMode.Open,
FileAccess.Read);
using(var streamReader = new StreamReader(fileStream, Encoding.UTF8)) {
firstLine = streamReader.ReadLine();
}
var values = firstLine.Split(',');
for (int i = 0; i < values.Length; i++) {
values[i] = values[i].Trim();
}
if (values.Length == 4)
{
int count=0;
IList<string> newList = new List<string> { "MXASSETInterface", "SRM_SaaS_ES", "EN", "AddChange" };
for (int i = 0; i < values.Length; i++)
{
if (newList.Contains(values[i]))
{
count++;
newList.Remove(values[i]);
}
}
if (count == 4)
{
Console.WriteLine("head is correct");
}
else
{
Console.WriteLine("head is incorrect");
}
}
The complete console application can be found with below code, which can be run direct
class Program
{
static void Main(string[] args)
{
try
{
String firstLine;
var fileStream = new FileStream(#"C:\Users\user\Desktop\AssetsImportCompleteSample.csv", FileMode.Open,
FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
firstLine = streamReader.ReadLine();
}
if (firstLine != null)
{
var values = firstLine.Split(',');
Console.WriteLine(firstLine);
for (int i = 0; i < values.Length; i++)
{
values[i] = values[i].Trim();
Console.WriteLine(values[i]);
}
if (values.Length == 4)
{
int count=0;
IList<string> newList = new List<string> { "MXASSETInterface", "SRM_SaaS_ES", "EN", "AddChange" };
for (int i = 0; i < values.Length; i++)
{
if (newList.Contains(values[i]))
{
count++;
newList.Remove(values[i]);
}
}
if (count == 4)
{
Console.WriteLine("head is correct");
}
else
{
Console.WriteLine("head is incorrect");
}
}
else
{
Console.WriteLine("header is Invalid");
}
}
else
{
Console.WriteLine("header is Invalid");
}
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Please check if file is available or path is correct", e.Message);
}
Console.ReadLine();
}
}
I suggest using CsvHelpet library for parsing the CSV file. It allows to define a class that represents a row in your file. Header names are property names by default or they can be mapped usimg fluent API.
var csv = new CsvReader( textReader ); var records = csv.GetRecords();
Get records will fail if some headers are missing.
I am writing a little tool for myself to merge PDF files using PDFSharp library. I am using the latest pre-release version (1.5) of PDFSharp.
I come across a problem where documents that are loaded into memory is not releasing when going out of scope. I tracked down this memory leak to the following part of the code:
using (var mergedDocument = new PdfDocument())
{
for (var i = 0; i < SelectedDocuments.Count; i++)
{
using (var document = PdfReader.Open(SelectedDocuments[i].FilePath, PdfDocumentOpenMode.Import))
{
for (var j = 0; j < document.PageCount; j++)
{
mergedDocument.AddPage(document.Pages[j]);
}
}
}
mergedDocument.Save(savePath);
}
An example would be I have 10 pdf documents which totals on 178 Mb. The merged document that is created is also around 178 Mb. When above code finishes executing memory usage holds at 356 Mb. When I merge more documents this memory leak keeps going up and eventually cause a crash.
I tried removing using statements and using Dispose() when I wanted the document to be released from memory, however it does not work as well.
Any help would be appreciated. Thank you.
Edit:
To be more precise:
var parentDirectory = Directory.GetParent(SelectedDocuments[0].FilePath);
var savePath = parentDirectory + "\\MergedDocument.pdf";
using (var mergedDocument = new PdfDocument())
{
for (var i = 0; i < SelectedDocuments.Count; i++)
{
using (var document = PdfReader.Open(SelectedDocuments[i].FilePath, PdfDocumentOpenMode.Import))
{
for (var j = 0; j < document.PageCount; j++)
{
mergedDocument.AddPage(document.Pages[j]);
}
}
}
mergedDocument.Save(savePath);
}
SelectedDocuments is a list which holds a bunch of file paths to the selected PDF files.
I ended up using iTextSharp instead with the following code to avoid memory issues:
var parentDirectory = Directory.GetParent(SelectedDocuments[0].FilePath);
var savePath = parentDirectory + "\\MergedDocument.pdf";
using (var fs = new FileStream(savePath, FileMode.Create))
{
using (var document = new Document())
{
using (var pdfCopy = new PdfCopy(document, fs))
{
document.Open();
for (var i = 0; i < SelectedDocuments.Count; i++)
{
using (var pdfReader = new PdfReader(SelectedDocuments[i].FilePath))
{
for (var page = 0; page < pdfReader.NumberOfPages;)
{
pdfCopy.AddPage(pdfCopy.GetImportedPage(pdfReader, ++page));
}
}
}
}
}
}
When I try to save each page as GIF using ABCpdf, only the first page is saved.
For example: I have a PDF that has 3 pages. I use ABCpdf to render each page to a stream, which is saved to disk. When I open the files in my destination folder, all 3 files show the first page content.
Here's my code:
using (Doc theDoc = new Doc())
{
XReadOptions options = new XReadOptions { ReadModule = ReadModuleType.Pdf };
theDoc.Read(inputbytearray, options);
using (MemoryStream ms = new MemoryStream())
{
theDoc.Rendering.DotsPerInch = 150;
int n = theDoc.PageCount;
for (int i = 1; i <= n; i++)
{
Guid FileName = Guid.NewGuid();
theDoc.Rect.String = theDoc.CropBox.String;
theDoc.Rendering.SaveAppend = (i != 1);
theDoc.Rendering.SaveCompression = XRendering.Compression.G4;
theDoc.PageNumber = i;
theDoc.Rendering.Save(string.Format("{0}.gif", FileName), ms);
using (var streamupload = new MemoryStream(ms.GetBuffer(), writable: false))
{
_BlobStorageService.UploadfromStream(FileName.ToString(), streamupload, STR_Gif, STR_Imagegif);
}
}
// theDoc.Clear();
}
}
The Rendering.SaveAppend property is only applicable when saving TIFF images. For GIFs you would need to save a separate image for each PDF page.
private void button1_Click(object sender, System.EventArgs e)
{
string theDir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + #"\files\";
// Create test PDF
using (Doc doc = new Doc())
{
for (int i = 1; i <= 3; i++)
{
doc.Page = doc.AddPage();
doc.AddHtml("<font size=24>PAGE " + i.ToString());
}
doc.Save(Path.Combine(theDir, "test.pdf"));
}
// Save PDF pages to GIF streams
using (Doc doc = new Doc())
{
doc.Read(Path.Combine(theDir, "test.pdf"));
for (int i = 1; i <= doc.PageCount; i++)
{
doc.PageNumber = i;
doc.Rect.String = doc.CropBox.String;
using (MemoryStream ms = new MemoryStream())
{
doc.Rendering.Save("dummy.gif", ms);
using (FileStream fs = File.Create(Path.Combine(theDir, "p" + i.ToString() + ".gif")))
{
ms.Seek(0, SeekOrigin.Begin);
ms.CopyTo(fs);
}
}
}
}
}
I am using the following code to write a file to the Desktop.
string submittedFilePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
int i = 0;
StreamWriter sw = null;
sw = new StreamWriter(submittedFilePath, false);
for (i = 0; i < PSOLib.table.Columns.Count - 1; i++)
{
sw.Write(PSOLib.table.Columns[i].ColumnName + ";");
}
sw.Write(PSOLib.table.Columns[i].ColumnName);
sw.WriteLine();
foreach (DataRow row in PSOLib.table.Rows)
{
object[] array = row.ItemArray;
for (i = 0; i < array.Length - 1; i++)
{
sw.Write(array[i].ToString() + ";");
}
sw.Write(array[i].ToString());
sw.WriteLine();
}
sw.Close();
However whenever I try to invoke the method I get:
Access to the path 'C:\\Users\\User\\Desktop' is denied.
System.UnauthorizedAccessException.
You didn't specify a file for your StreamWriter, but a folder.
This should do it:
string submittedFilePath =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\myFile.txt.";
I use VS 2008 SP1 in Windows XP.
I have updated ICSharpCode.SharpZipLib.dll from older 0.85.4.369 to new 0.86.0.518.
I have been using it successfully for older 0.85.4.369.
I have been able to zip and unzip both files and folders without a problem - well, until now.
But now, I get error "EOF In Header" when read a ZIP file that I have generated using ICSharpCode.SharpZipLib.dll too.
My code C# is the same, no changes about it.
Fails: theEntry = z.GetNextEntry();
public static string LeerEtiquetaEmpaquetado(string zipFic)
{
ZipInputStream z = null;
DatosEmpaquetado datEmp;
try
{
z = new ZipInputStream(File.OpenRead(zipFic));
ZipEntry theEntry;
do
{
theEntry = z.GetNextEntry();
if (theEntry != null)
{
if (theEntry.Name.EndsWith("empaquetado.xml"))
{
using (MemoryStream memWrt = new MemoryStream())
{
int size = 2048;
byte[] data = new byte[2048];
do
{
size = z.Read(data, 0, data.Length);
if ((size > 0))
{
memWrt.Write(data, 0, size);
}
else
{
break;
}
} while (true);
datEmp = LeerEmpaquetado(memWrt);
return datEmp.Etiqueta;
}
break;
}
}
else
{
break;
}
} while (true);
return null;
}
catch (Exception exc)
{
System.Diagnostics.Trace.WriteLine("Excepción: " + exc.Message);
System.Diagnostics.Trace.WriteLine(exc.StackTrace);
throw;
}
finally
{
if (z != null)
{
z.Close();
z.Dispose();
}
}
}
The ICSharpCode.SharpZipLib.dll ( 0.86.0.518 ) seems unable to open the ZIPs it just created.
Very Strange thing is:
The newly-created files open just fine in WinRAR.
ZIP files created with previous versions of the DLL open just fine with the new DLL.
Code for ZIP file:
public static void EmpaquetarProyecto(string dirOutput, string nombre, string dirDestino)
{
string dirActual = Environment.CurrentDirectory;
Environment.CurrentDirectory = dirOutput;
string[] fileNames = Directory.GetFiles(".", "*.*", SearchOption.AllDirectories);
try
{
Crc32 objCrc32 = new Crc32();
ZipOutputStream strmZipOutputStream;
nombre = Path.Combine(dirDestino, nombre + ".zip");
strmZipOutputStream = new ZipOutputStream(File.Create(nombre));
strmZipOutputStream.SetLevel(6);
foreach (string aux in fileNames)
{
string strFile = aux;
if (strFile.StartsWith(".\\"))
{
strFile = strFile.Substring(2);
}
FileStream strmFile = File.OpenRead(strFile);
byte[] abyBuffer = new byte[(Convert.ToInt32(strmFile.Length))];
strmFile.Read(abyBuffer, 0, abyBuffer.Length);
ZipEntry theEntry = new ZipEntry(strFile);
FileInfo fi = new FileInfo(strFile);
theEntry.DateTime = fi.LastWriteTime;
theEntry.Size = strmFile.Length;
strmFile.Close();
objCrc32.Reset();
objCrc32.Update(abyBuffer);
theEntry.Crc = objCrc32.Value;
strmZipOutputStream.PutNextEntry(theEntry);
strmZipOutputStream.Write(abyBuffer, 0, abyBuffer.Length);
}
strmZipOutputStream.Finish();
strmZipOutputStream.Close();
}
finally
{
Environment.CurrentDirectory = dirActual;
}
}
Perhaps error is aboutCRC, I think.
Any ideas about it? any changes in my code ?
edit: If delete code about CRC , it works, but why ??