Why my code can not find the path in project? - c#

I am using this to merge 2 pad files:
public static void MergePages(string outputPdfPath, string[] lstFiles)
{
lstFiles = new string[2] { #"Downloads\Certificates\119.FDV-3686.pdf",
#"Downloads\Certificates\119.FDV-3686.pdf" };
outputPdfPath = #"Downloads\Certificates\";
PdfReader reader = null;
Document sourceDocument = null;
PdfCopy pdfCopyProvider = null;
PdfImportedPage importedPage;
sourceDocument = new Document();
pdfCopyProvider = new PdfCopy(sourceDocument,
new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));
sourceDocument.Open();
try
{
for (int f = 0; f < lstFiles.Length - 1; f++)
{
int pages = 1;
reader = new PdfReader(lstFiles[f]);
//Add pages of current file
for (int i = 1; i <= pages; i++)
{
importedPage = pdfCopyProvider.GetImportedPage(reader, i);
pdfCopyProvider.AddPage(importedPage);
}
reader.Close();
}
sourceDocument.Close();
}
catch (Exception ex)
{
throw ex;
}
}
The 2 files exists in my project directory but it throws error:
Could not find a part of the path 'C:\Program Files (x86)\IIS Express\~\Downloads\Certificates\119.FDV-3686.pdf'.
I don't understand why it goes to C drive since files are in the same project.

(1) One problem might be that your design-time pdf files are not copied to application output directory during compilation. Therefore they are not available run-time.
If you want to copy file(s) from your solution folder to application output directory, you can set to file property "Copy to Output directory" to "Copy always" or "Copy if newer". More discussion about topic is found i.e here.
File properties can be set by selecting file under solution explorer.
(2) Another problem is that you do not set root directory of file path. I recommend you to express file path with following style:
var rootLocation = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase.ToString()).LocalPath);
var filePath1 = Path.Combine(rootLocation,#"Downloads\Certificates\filename1.pdf");
var filePath2 = Path.Combine(rootLocation,#"Downloads\Certificates\filename2.pdf");
..

Related

(Deleting a file/emptying it) C#

Basically I am trying to make a program that empties or even deletes a certain file, the thing is, this file is about 3 or 4 or so folders past the macromedia folder, and it can be it different named folders for anyone, so that is why the string[] files is done like that, it just checks for basically "FlashGame.sol" in EVERY folder after the macromedia folder.
I commented where I need help, I basically need to empty the contents of the file, or just flat out delete it.
private void button1_Click(object sender, EventArgs e)
{
string path = textBox1.Text + "/AppData/Roaming/Macromedia"; //the person using the program has to type in the beginning of the directory, C:/Users/Mike for example
bool Exists = Directory.Exists(path);
try
{
if (Exists)
{
string[] files = Directory.GetFiles(path, "*FlashGame.sol", SearchOption.AllDirectories);
string[] array = files;
for (int i = 0; i < array.Length; i++)
{
string info;
string text = array[i];
using (StreamReader streamReader = new StreamReader(text))
{
info = streamReader.ReadToEnd();
//erase the contents of the file here or even delete it
}
}
}
}
catch
{
MessageBox.Show("The given directory was not found", "Error", MessageBoxButtons.OK);
}
}
You can clear a file this way:
System.IO.File.WriteAllText(#"file.path",string.Empty);
So you should probably change your Code to:
string[] files = Directory.GetFiles(path, "*FlashGame.sol", SearchOption.AllDirectories);
foreach (var file in files)
{
System.IO.File.WriteAllText(file, string.Empty);
}
Also take a look at Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), which gives the appdata directory of the current user.
Also never catching a Exception without handling it correctly. You already know, if the directory exists via your Exists Variable.
string path = Environment.ExpandEnvironmentVariables(#"%AppData%\Macromedia\"); // Example C:\Users\Mike\AppData\Roaming\Macromedia\
if (Directory.Exists(path)) {
string[] files = Directory.EnumerateFiles(path, "*FlashGame.sol", SearchOption.AllDirectories);
foreach (string file in files) {
try {
File.Delete(file);
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
}

Pdfsharp Out of Memory Exception when Combine Multi Pdf File

I have to convert into a single pdf a large number (but undefined) pdf into one for this, I'm using the code PDFsharp here.
// Get some file names
string[] files = filesToPrint.ToArray();
// Open the output document
PdfDocument outputDocument = new PdfDocument();
PdfPage newPage;
int nProcessedFile = 0;
int nMemoryFile = 5;
int nStepConverted = 0;
String sNameLastCombineFile = "";
// Iterate files
foreach (string file in files)
{
// Open the document to import pages from it.
PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import);
// Iterate pages
int count = inputDocument.PageCount;
for (int idx = 0; idx < count; idx++)
{
// Get the page from the external document...
PdfPage page = inputDocument.Pages[idx];
// ...and add it to the output document.
outputDocument.AddPage(page);
}
nProcessedFile++;
if (nProcessedFile >= nMemoryFile)
{
//nProcessedFile = 0;
//nStepConverted++;
//sNameLastCombineFile = "ConcatenatedDocument" + nStepConverted.ToString() + " _tempfile.pdf";
//outputDocument.Save(sNameLastCombineFile);
//outputDocument.Close();
}
}
// Save the document...
const string filename = "ConcatenatedDocument1_tempfile.pdf";
outputDocument.Save(filename);
// ...and start a viewer.
Process.Start(filename);
For small numbers of files the code works but then at some point
generates an exception of out of memory
is there a solution?
p.s
I was thinking of saving the files in step and then the remaining aggiungingere so liebrare memory but I can not find the way.
UPDATE1:
if (nProcessedFile >= nMemoryFile)
{
nProcessedFile = 0;
//nStepConverted++;
sNameLastCombineFile = "ConcatenatedDocument" + nStepConverted.ToString() + " _tempfile.pdf";
outputDocument.Save(sNameLastCombineFile);
outputDocument.Close();
outputDocument = PdfReader.Open(sNameLastCombineFile,PdfDocumentOpenMode.Modify);
}
UPDATE 2 versione 1.32
Complete example
Error on line:
PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import);
Text error:
Cannot handle iref streams. The current implementation of PDFsharp cannot handle this PDF feature introduced with Acrobat 6.
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<String> filesToPrint = new List<string>();
filesToPrint = Directory.GetFiles(#"D:\Downloads\RACCOLTA\FILE PDF", "*.pdf").ToList();
// Get some file names
string[] files = filesToPrint.ToArray();
// Open the output document
PdfDocument outputDocument = new PdfDocument();
PdfPage newPage;
int nProcessedFile = 0;
int nMemoryFile = 5;
int nStepConverted = 0;
String sNameLastCombineFile = "";
try
{
// Iterate files
foreach (string file in files)
{
// Open the document to import pages from it.
PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import);
// Iterate pages
int count = inputDocument.PageCount;
for (int idx = 0; idx < count; idx++)
{
// Get the page from the external document...
PdfPage page = inputDocument.Pages[idx];
// ...and add it to the output document.
outputDocument.AddPage(page);
}
nProcessedFile++;
if (nProcessedFile >= nMemoryFile)
{
nProcessedFile = 0;
//nStepConverted++;
sNameLastCombineFile = "ConcatenatedDocument" + nStepConverted.ToString() + " _tempfile.pdf";
outputDocument.Save(sNameLastCombineFile);
outputDocument.Close();
inputDocument = PdfReader.Open(sNameLastCombineFile , PdfDocumentOpenMode.Modify);
}
}
// Save the document...
const string filename = "ConcatenatedDocument1_tempfile.pdf";
outputDocument.Save(filename);
// ...and start a viewer.
Process.Start(filename);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
}
}
UPDATE3
Code that generate exception out of memory
int count = inputDocument.PageCount;
for (int idx = 0; idx < count; idx++)
{
// Get the page from the external document...
newPage = inputDocument.Pages[idx];
// ...and add it to the output document.
outputDocument.AddPage(newPage);
newPage.Close();
}
I can not exactly which row general exception
I had a simular issue, saving, closing and reopening the PdfDocument did not really help.
I am adding al lot (100+) large (upto 5Mb) images (tiff, jpg, etc) to a pdf document where every images has its own page. It crashed around image #50. After the save-close-reopen it did finish the whole document but was still getting close to max memory, around 3Gb. Some more images and it would still crash.
After more refining, I implemented a using for the XGraphics object, it was a little better again but not much.
The big step forward was disposing of the XImage within the loop! After that the application never used more than 100-200Kb, I removed the save-close-reopen for the PdfDocument and it was no problem.
After saving and closing outputDocument (the code is commented out in your snippet), you have to open outputDocument again, using PdfDocumentOpenMode.Modify.
It could help to add using(...) for the inputDocument.
If your code is running as a 32-bit process, then switching to 64 bit will allow your process to use more than 2 GB of RAM (assuming your computer has more than 2 GB RAM).
Update: The message "Cannot handle iref streams" means you have to use PDFsharp 1.50 Prerelease, available on NuGet.

How to edit Text file in Resources Folder of Window form c#

I am trying to Edit a text file which is consist in resources folder of window form project. C#.
I am using this code but it is not writing over text file. No errors come from this
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Namespace.Properties.Resources.textfile))
{
for (int i = 0; i < res2.Count(); i++)
{
label3.Text = "Updating ... ";
label3.Visible = true;
label3.Refresh();
file.WriteLine("asdasD");
}
file.Close();
}
As #LarsTech states in this answer, what you are trying to do is not recommended. Resource files are not meant to be written to--they should only be read from. If you want a place to put files, put them somewhere like Environment.SpecialFolders.
You could also use the AppData folder on the user's computer, which is typically used for exactly what you are trying to achieve:
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "textfile.txt");
using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName))
{
//if the file doesn't exist, create it
if (!File.Exists(fileName))
File.Create(fileName);
for (int i = 0; i < res2.Count(); i++)
{
label3.Text = "Updating ... ";
label3.Visible = true;
label3.Refresh();
file.WriteLine("asdasD");
}
}
As you can see, I removed the file.Close() since it isn't necessary if you are using the using block. You can do this if you are using a member which implements the IDisposable interface, which StreamWriter does.
This should take care of everything for you. You won't have to create any files or worry about where they are.
I am able to write and then read a file using your code in a console application. Can you run this code (console application) and tell me if you have any exception ?
static void Main(string[] args)
{
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "textfile.txt");
using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName))
{
//if the file doesn't exist, create it
if (!File.Exists(fileName))
File.Create(fileName);
for (int i = 0; i < 2; i++)
{
file.WriteLine("asdas2");
}
}
using(System.IO.StreamReader fr = new StreamReader(fileName))
{
Console.WriteLine(fr.ReadToEnd());
}
}
Note, if you are trying to append to the existing file (write at the end of it and keep existing content), you need to use System.IO.StreamWriter(fileName, true).

How to get files from exact subdirectories

I've managed to get files out of "root" folder subdirectories, but I also get files from these subdirectories directories2, which I don't want to.
Example: RootDirectory>Subdirectories (wanted files)>directories2 (unwanted files)
I've used this code:
public void ReadDirectoryContent()
{
var s1 = Directory.GetFiles(RootDirectory, "*", SearchOption.AllDirectories);
{
for (int i = 0; i <= s1.Length - 1; i++)
FileInfo f = new FileInfo(s1[i]);
. . . etc
}
}
Try this :
var filesInDirectSubDirs = Directory.GetDirectories(RootDirectory)
.SelectMany(d=>Directory.GetFiles(d));
foreach(var file in filesInDirectSubDirs)
{
// Do something with the file
var fi = new FileInfo(file);
ProcessFile(fi);
}
The idea is to first select 1st level of subdirectories, then "aggregate" all files using Enumerable.SelectMany method
You have to change SearchOption.AllDirectories to SearchOption.TopDirectoryOnly, because the first one means that it gets the files from the current directory and all the subdirectories.
EDIT:
The op wants to search in direct child subdirectories, not the root
directory.
public void ReadDirectoryContent()
{
var subdirectories = Directory.GetDirectories(RootDirectory);
List<string> files = new List<string>();
for(int i = 0; i < subdirectories.Length; i++)
files.Concat(Directory.GetFiles(subdirectories[i], "*", SearchOption.TopDirectoryOnly));
}

Opening folder with no law to escape

how open a folder from winforms in this way that user couldn't move from this folder to another?
He could only remove or add files to this folder.
And he could close this folder and return to his winforms app.
It's not really possible (I assume you mean open it in Explorer). Your best bet is to have him run as a user that only has permissions to open that folder. What I mean is that you should try and solve this using the inbuilt Windows ACL system.
Perhaps if you provide more details we can help solve the underlying issue.
path = folderBrowserDialog1.SelectedPath;
ImageList imageList1 = new ImageList();
imageList1.ImageSize = new Size(256, 256);
imageList1.ColorDepth = ColorDepth.Depth24Bit;
string[] iconFiles = Directory.GetFiles(path, "*.jpg");
foreach (string iconFile in iconFiles)
{
try
{
imageList1.Images.Add(Image.FromFile(iconFile));
}
catch
{
MessageBox("Error","");
}
}
this.listView1.View = View.LargeIcon;
this.listView1.LargeImageList = imageList1;
for (int j = 0; j < imageList1.Images.Count; j++)
{
ListViewItem item = new ListViewItem();
item.ImageIndex = j;
this.listView1.Items.Add(item);
}
This displays thumbnails of files. How to stick this with files? Deleting, renaming??

Categories

Resources