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??
Related
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");
..
What I have here is the user select a folder full of .txt files from a external drive and a dummy file is made with the filename to a local folder.
I have 2 questions regarding the code below.
How do I verify that the user select a specific folder?
How do I remove the .txt extension? The code copies the file name and creates the files but its labeled "text.txt.png" but I need it to read "text.png".
int g;
private void folderSelect()
{
FolderBrowserDialog folder = new FolderBrowserDialog();
folder.RootFolder = Environment.SpecialFolder.MyComputer;
folder.ShowNewFolderButton = false;
folder.Description = "Select Folder";
if (folder.ShowDialog() == DialogResult.OK)
{
DirectoryInfo files = new DirectoryInfo(folder.SelectedPath);
FileInfo[] textFiles = files.GetFiles("*.txt");
while (g < textFiles.Length)
{
if (g <= textFiles.Length)
{
File.Create("path/" + (textFiles[g].Name + ".png"));
g++;
}
else
{
break;
}
}
}
Note: I tried using Path.GetFileNameWithoutExtension to remove the extension but Im not sure if i was using it correctly.
Any help would be appreciated. Thank you in advance.
const string NEW_PATH = "path/";
if (!Directory.Exists(NEW_PATH))
Directory.CreateDirectory(NEW_PATH);
const string PATH_TO_CHECK = "correctpath";
FolderBrowserDialog folder = new FolderBrowserDialog();
folder.RootFolder = Environment.SpecialFolder.MyComputer;
folder.ShowNewFolderButton = false;
folder.Description = "Select Folder";
if (folder.ShowDialog() == DialogResult.OK)
{
string pathPastDrive = folder.SelectedPath.Substring(Path.GetPathRoot(folder.SelectedPath).Length).ToLower();
// Here it depends on whether you want to check (1) that the path is EXACTLY what you want,
// or (2) whether the selected path just needs to END in the path that you want.
/*1*/ if (!pathPastDrive == PATH_TO_CHECK)
/*2*/ if (!pathPastDrive.EndsWith(PATH_TO_CHECK))
return; // or you can throw an exception if you want
foreach (string textFile in Directory.GetFiles(folder.SelectedPath, "*.txt"))
File.Create(NEW_PATH + Path.GetFileNameWithoutExtension(textFile) + ".png");
}
You can use GetFileNameWithoutExtension, and it makes it pretty easy.
Also, if you're already sure that your new folder exists, then you can elide the first three lines and replace NEW_PATH with "path/" in the last line.
To see the returned path just use the SelectedPath property, then you can compare it to whatever you had in mind. The # before the path just means I don't have to escape any characters, it's the same as "C:\\MyPath".
FolderBrowserDialog folder = new FolderBrowserDialog();
if (folder.ShowDialog() == DialogResult.OK)
{
if (folder.SelectedPath == #"C:\MyPath")
{
// DO SOMETHING
}
}
You already hit the nail on the head about the file name without extension, change this line:
File.Create("path/" + (textFiles[g].Name + ".png"));
To this:
File.Create("path/" + (Path.GetFileNameWithoutExtension(textFiles[g].Name) + ".png"));
Edit:
To get the folder name you already have the DirectoryInfo object so just use that:
DirectoryInfo files = new DirectoryInfo(folder.SelectedPath);
string folderName = files.Name;
I am trying to load pictures that are in a certain folder (camera) into my application using a listview and pictureList. For some reason the files are loaded but do not appear in the listview.
This is the code I have so far:
try
{
listView1.View = View.LargeIcon;
imageList1.ImageSize = new Size(32, 32);
listView1.LargeImageList = imageList1;
DirectoryInfo directory = new DirectoryInfo(#"C:\");
FileInfo[] Archives = directory.GetFiles("*.JPG");
foreach (FileInfo fileinfo in Archives)
{
imageList1.Images.Add(Image.FromFile(fileinfo.FullName));
}
listView1.Update();
MessageBox.Show("I found " + imageList1.Images.Count.ToString() + " images!");
}
catch
{
MessageBox.Show("Something went wrong!");
}
Note that the messagebox is showing me the correct number of files, so I suppose I have some part right. Any clues what might be wrong?
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).
I have developed an application that loaded many images in a listview using ImageList in c# .net framework 4. The images are also compressed. When many many images are loaded and compressed then it takes a long time. So I call the method in backgroundworker. In the backgroundworker I had to add images to ImageList and add ImageList to ListView. So I have used safeinvoke() method listView1.SafeInvoke(d=>d.Items.Add(item)).
Everything works fine. Images are displayed one by one in the listview.
But the release of the application doesn’t work properly in some pc and properly works in some other pc. Doesn’t work properly means, If 100 images are browsed using OpenFileDialog to load then some images are loaded and added to listview and then the loading is automatically stopped without adding all images to the listview and no exception shows.
I have spent many times to solve this problem but couldn’t figure out the problem. . Where is the problem? Can anybody help me?
private void bgwLoading_DoWork(object sender, DoWorkEventArgs e)
{
ArrayList a = (ArrayList)e.Argument;
string[] fileNames = (string[])a[0];
this.loadMultiImages(fileNames);
}
private void loadMultiImages(string[] fileNames)
{
int i = 1;
int totalFiles = fileNames.Count();
foreach (string flName in fileNames)
{
if (!flName.Contains("Thumbs.db"))
{
Bitmap newBtmap = (Bitmap)Image.FromFile(flName);
FileInfo fi = new FileInfo(flName);
long l = fi.Length;
if (l > compressSize)
{
newBtmap = resizeImage(newBtmap, 1024,768) ;
newBtmap = saveJpeg(IMAGE_PATH + (SCANNING_NUMBER +
) + ".jpg", newBtmap, IMAGE_QUALITY);
}
else
{
File.Copy(flName, TEMP_IMAGE_PATH + (SCANNING_NUMBER + 1) + ".jpg");
}
if (!bgwLoading.CancellationPending)
{
CommonInformation.SCANNING_NUMBER++;
this.SafeInvoke(d => d.addItemToLvImageContainer(newBtmap));
bgwLoading.ReportProgress((int)Math.Round((double)i / (double)
(totalFiles) * 100));
i++;
}
}
}
}
}
public void addItemToLvImageContainer(Bitmap newBtmap)
{
imageList.Images.Add(newBtmap);
ListViewItem item;
item = new ListViewItem();
item.ImageIndex = SCANNING_NUMBER - 1;
item.Text = SCANNING_NUMBER.ToString();
lvImageContainer.Items.Add(item);
lvImageContainer.Items[item.ImageIndex].Focused = true;
}
To find out the error I have modified the code as follows:
I have commented the two lines
//newBtmap = resizeImage(newBtmap, 1024, 768);
// newBtmap = saveJpeg(IMAGE_PATH + scanning_number + ".jpg", newBtmap, Image_Quality );
and added try-catch as follows:
try
{
Bitmap newBtmap = (Bitmap)Image.FromFile(flName);
File.Copy(flName, CommonInformation.TEMP_IMAGE_PATH +
(CommonInformation.SCANNING_NUMBER + 1) + ".jpg");
if (!bgwLoading.CancellationPending)
{
this.SafeInvoke(d => d.imageList.Images.Add(newBtmap));
ListViewItem item;
item = new ListViewItem();
CommonInformation.SCANNING_NUMBER++;
item.ImageIndex = CommonInformation.SCANNING_NUMBER - 1;
item.Text = CommonInformation.SCANNING_NUMBER.ToString();
this.SafeInvoke(d => d.lvImageContainer.Items.Add(item));
bgwLoading.ReportProgress((int)Math.Round((double)i /
(double)(totalFiles) * 100));
this.safeInvoke(d=>d.addItemImageContainer(newBtmap))
catch (Exception ex)
{
MessageBox.Show( ex.Message);
}
It shows the error message after loading some images as "OutOfMemoryException"
Most probably the following line creates the exception:
Bitmap newBtmap = (Bitmap)Image.FromFile(flName);
But the image files are not corrupted and their file extension is .JPG.
How to get rid of this problem?
I have no answer, but i have some suggestions:
Check .NET framework version on computers with problems
Check, if you have permissions for files you trying to read
Use "try-catch" when you accessing files
And questions:
Is this project written in older version of .NET and migrated/upgraded to .NET 4.0?
Are you using any non-built-in assemblies or external dll's for image processing?