I followed Joe's idea on how to use CommonOpenFileDialog to open a folder / file here
I've installed the package Microsoft.WindowsAPICodePack-Shell in my project and included this line as well: using Microsoft.WindowsAPICodePack.Dialogs;
The code:
private void Button_Click(object sender, RoutedEventArgs e)
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.IsFolderPicker = true;
dialog.Multiselect = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
MessageBox.Show("You selected: " + dialog.FileName);
}
}
However, there are some methods / attributes that I could not use.
I screenshotted the errors I got: errors
Is there an updated documentation on how to use the CommonOpenFileDialog package so that I can refer to it?
This works, you must simply install it using Install NuGet packages. Search for WindowsAPICodePack-Shell, then install it for your project.
Next, make sure the Microsoft.WindowsAPICodePack and Microsoft.WindowsAPICodePack.Shell DLLs are visible in the dependency list.
Make sure there is using Microsoft.WindowsAPICodePack.Dialogs; declaration in the file where you are using the control.
If you are using it in a console application, add [STAThread] right above the static void Main(string[] args).
You could use the System.Windows.Forms.OpenFileDialog for opening files, it contains the properties InitialDirectory and Multiselect.
For opening folders, you could use System.Windows.Forms.FolderBrowserDialog . With this class, you would need to use the property RootFolder to choose where the browsing starts from.
Related
I can't use "Zipfile" class in the name space "System.IO.Compression" my code is :
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.zip";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest,true);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
}
the error is :
The name 'zipfile' does not exist in the current context
How I can solve it ?
You need an extra reference for this; the most convenient way to do this is via the NuGet package System.IO.Compression.ZipFile
<!-- Version here correct at time of writing, but please check for latest -->
<PackageReference Include="System.IO.Compression.ZipFile" Version="4.3.0" />
If you are working on .NET Framework without NuGet, you need to add a dll reference to the assembly, "System.IO.Compression.FileSystem.dll" - and ensure you are using at least .NET 4.5 (since it doesn't exist in earlier frameworks).
For info, you can find the assembly and .NET version(s) from MSDN
For those who are green programmers in .NET, to add the DLL reference as MarcGravell noted, you follow these steps:
To add a reference in Visual C#
In Solution Explorer, right-click the project node and click Add Reference.
In the Add Reference dialog box, select the tab indicating the type of component you want to reference.
Select the components you want to reference, and then click OK.
From the MSDN Article, How to: Add or Remove References By Using the Add Reference Dialog Box.
you can use an external package if you cant upgrade to 4.5. One such is Ionic.Zip.dll from DotNetZipLib.
using Ionic.Zip;
you can download it here, its free. http://dotnetzip.codeplex.com/
Just go to References and add "System.IO.Compression.FileSystem".
In solution explorer, right-click References, then click to expand assemblies, find System.IO.Compression.FileSystem and make sure it's checked. Then you can use it in your class - using System.IO.Compression;
Add Reference Assembly Screenshot
A solution that helped me:
Go to Tools > NuGet Package Manager > Manage NuGet Packaged for Solution... > Browse >
Search for System.IO.Compression.ZipFile and install it
System.IO.Compression is now available as a nuget package maintained by Microsoft.
To use ZipFile you need to download System.IO.Compression.ZipFile nuget package.
I know this is an old thread, but I just cannot steer away from posting some useful info on this. I see the Zip question come up a lot and this answers nearlly most of the common questions.
To get around framework issues of using 4.5+... Their is a ZipStorer class created by jaime-olivares: https://github.com/jaime-olivares/zipstorer, he also has added an example of how to use this class as well and has also added an example of how to search for a specific filename as well.
And for reference on how to use this and iterate through for a certain file extension as example you could do this:
#region
/// <summary>
/// Custom Method - Check if 'string' has '.png' or '.PNG' extension.
/// </summary>
static bool HasPNGExtension(string filename)
{
return Path.GetExtension(filename).Equals(".png", StringComparison.InvariantCultureIgnoreCase)
|| Path.GetExtension(filename).Equals(".PNG", StringComparison.InvariantCultureIgnoreCase);
}
#endregion
private void button1_Click(object sender, EventArgs e)
{
//NOTE: I recommend you add path checking first here, added the below as example ONLY.
string ZIPfileLocationHere = #"C:\Users\Name\Desktop\test.zip";
string EXTRACTIONLocationHere = #"C:\Users\Name\Desktop";
//Opens existing zip file.
ZipStorer zip = ZipStorer.Open(ZIPfileLocationHere, FileAccess.Read);
//Read all directory contents.
List<ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();
foreach (ZipStorer.ZipFileEntry entry in dir)
{
try
{
//If the files in the zip are "*.png or *.PNG" extract them.
string path = Path.Combine(EXTRACTIONLocationHere, (entry.FilenameInZip));
if (HasPNGExtension(path))
{
//Extract the file.
zip.ExtractFile(entry, path);
}
}
catch (InvalidDataException)
{
MessageBox.Show("Error: The ZIP file is invalid or corrupted");
continue;
}
catch
{
MessageBox.Show("Error: An unknown error ocurred while processing the ZIP file.");
continue;
}
}
zip.Close();
}
Add System.IO.Compression.ZipFile as nuget reference it is working
The issue here is that you just Added the reference to System.IO.Compression it is missing the reference to System.IO.Compression.Filesystem.dll
And you need to do it on .net 4.5 or later (because it doesn't exist on older versions).
I just posted a script on TechNet Maybe somebody would find it useful it requires .net 4.5 or 4.7
https://gallery.technet.microsoft.com/scriptcenter/Create-a-Zip-file-from-a-b23a7530
Is there anyway that a reference can be added to a solution programmatically?
I have an add-in button, when the user presses it, I want a reference to be added.
The reason is, I have created a piece of software that I want to be integrated into any given VS program (if the developer wants it), they would simply click the add-in button and the reference would be loaded in the current solution.
Is this possible?
Something like this I haven't tested it
get the environment
EnvDTE80.DTE2 pEnv = null;
Type myType = Type.GetTypeFromProgID("VisualStudio.DTE.8.0");
pEnv = (EnvDTE80.DTE2)Activator.CreateInstance(myType, true);
get the solution.
Solution2 pSolution = (Solution2)pEnv.VS.Solution;
get the project that you want
Project pProject = pSolution.Projects[0];
add the reference
pProject.References.Add(string referenceFilePath);
There is an example on CodeProject.
The functionality is contained within a single class elRefManager and the method to call is CheckReferences. The code can be looked at here by selecting the elRefManager.cs file on the left hand side.
As seen in the article you could do...
private void button1_Click(object sender, System.EventArgs e)
{
int ec;
ec=elRefManager.CheckReferences(null, new string[] {textBox1.Text});
if (ec<0)
MessageBox.Show("An error occurred adding this reference");
if (ec>0)
MessageBox.Show("Could not add " + textBox1.Text +
"\nCheck its spelling and try again");
}
System.Assembly.load Allows you to call functions in a library that were not built with your program.
If you want to add a reference to the project so that its in the solution you can use the following. Basically the same as #Scots answer.
I did it in a macro which is vb but I'm sure you can get the idea
DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate()
Dim objProject As EnvDTE.Project
Dim i As Long
i = DTE.Solution.Projects.Count
For Each objProject In DTE.Solution.Projects
If (objProject.Name() = "csCA") Then
Dim vsproj As VSLangProj.VSProject
vsproj = objProject.Object
vsproj.References.Add("C:\Users\test.dll")
End If
Next
I have an application which has several tabs. I am trying to add logging with NLog where the output is directed to a richtextbox.
My main form is an instance of a class MyNamespace.MainWindow and its name is MainWindow1. It has a tab and in that tab I have a RichTextBox called rtbLogBox
I have imported WpfRichTextBox extension from NuGetand place this piece of code in the MainWindow class's loaded event
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if(logger == null) logger = LogManager.GetCurrentClassLogger();
WpfRichTextBoxTarget rtbTarget = new WpfRichTextBoxTarget
{
Name = "rtbLog",
ControlName = "rtbLogBox",
FormName = "MainWindow"
};
LogManager.Configuration.AddTarget(rtbTarget);
LogManager.Configuration.AddRule(LogLevel.Info, LogLevel.Fatal, rtbTarget.Name);
logger.Info("This");
}
The problem is that this does not produce any outputs in the RichTextBox control.
I have an output to a file in addition to this and that target gets the log when I run the app.
Since the logger is created before you are changing the LogManager's configuration, you need to notify the logger of the change.
Calling LogManager.ReconfigExistingLoggers() should do the trick.
Documentation is here.
You can also use my wpf control. (https://github.com/dojo90/NLogViewer). There is also a nuget package available.
I want to create simple toast notification to action center in windows 10 from this example. But I got problem on Step 2:
using Windows.UI.Notifications;
It`s missing. But I have spent a lot of time to find it and got no result. I really have no idea where I can find or at least download it.
What I tried:
After long search I found Windows.UI.dll in C:\Windows\System32 but when I try to add it as reference into project I got this error. Even after I tried to copy it and made this fully accessible nothing changed
I tried to reinstall .Net (I`m using 4.5.2)
Installed Windows 10 SDK
Tried to import with global
Added
<PropertyGroup>
<TargetPlatformVersion>10.0</TargetPlatformVersion>
</PropertyGroup>
Added System.Runtime.dll reference
Example code which probably is useless for you:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Toolkit.Uwp.Notifications;
using Microsoft.QueryStringDotNET;
using Windows.UI.Notifications;
namespace MessagerClient.Notifications {
class DefaultWindowsNotification {
public static void notificationTest() {
string title = "Andrew sent you a picture";
string content = "Check this out, Happy Canyon in Utah!";
string image = "http://blogs.msdn.com/something.jpg";
string logo = "ms-appdata:///local/Andrew.jpg";
ToastVisual visual = new ToastVisual() {
BindingGeneric = new ToastBindingGeneric() {
Children =
{
new AdaptiveText()
{
Text = title
},
new AdaptiveText()
{
Text = content
},
new AdaptiveImage()
{
Source = image
}
},
AppLogoOverride = new ToastGenericAppLogo() {
Source = logo,
HintCrop = ToastGenericAppLogoCrop.Circle
}
}
};
Console.WriteLine("NOTIFICATION");
//Can`t use because of Windows.UI library
ToastNotificationManager.CreateToastNotifier().Show(visual);
}
}
}
You have to fight Visual Studio pretty hard to use these UWP contracts in a Winforms app. You got off on the wrong foot right away with the wrong TargetPlatformVersion, pretty hard to recover from that. Full steps to take:
Edit the .csproj file with a text editor, Notepad will do. Insert this:
<PropertyGroup>
<TargetPlatformVersion>10.0.10586</TargetPlatformVersion>
</PropertyGroup>
Which assumes you have the 10586 SDK version installed on your machine. Current right now, these versions change quickly. Double-check by looking in the C:\Program Files (x86)\Windows Kits\10\Include with Explorer, you see the installed versions listed in that directory.
Open the Winforms project, use Project > Add Reference > Windows tab > tick the Windows.Data and the Windows.UI contract. Add Reference again and use the Browse tab to select System.Runtime. I picked the one in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\ .NETFramework\v4.6.1\Facades. This reference displays with a warning icon, not sure what it is trying to say but it doesn't appear to have any side-effects.
Test it by dropping a button on the form, double-click to add the Click event handler. The most basic code:
using Windows.UI.Notifications;
...
private void button1_Click(object sender, EventArgs e) {
var xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
var text = xml.GetElementsByTagName("text");
text[0].AppendChild(xml.CreateTextNode("Hello world"));
var toast = new ToastNotification(xml);
ToastNotificationManager.CreateToastNotifier("anythinggoeshere").Show(toast);
}
Embellish by using a different ToastTemplateType to add an image or more lines of text. Do keep in mind that your program can only work on a Win10 machine.
If anyone should happen to stumble on this, see this similar but newer post -
Toast Notifications in Win Forms .NET 4.5
Read Stepan Hakobyan's comment at the bottom.
Essentially, I'm seeing the same thing. This code runs, I can step through it line by line with no exceptions but the toast notification is never shown within a Form app.
I made a small program in c# with a button that is supposed to open another .exe file.
It works fine if I use:
private void start_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Process.Start(#"path to file");
}
But not if I want it to run an .exe from the same folder, i basically wanted something like:
private void start_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Process.Start(#"program.exe");
}
What am I missing, I've tried a solution from this website:
var startIngo = new ProcessStartInfo();
startIngo.WorkingDirectory = // working directory
// set additional properties
Process proc = Process.Start(startIngo);
But Visual c# doesn't recognize "ProcessStartInfo" at all...
What your looking for is:
Application.StartupPath
It will return the startup path that your executable was started in.
If you are using WPF, try this instead:
String appStartPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
You can do:
var startupPath = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetEntryAssembly().Location);
var programPath = System.IO.Path.Combine(startupPath, "program.exe");
System.Diagnostics.Process.Start(programPath);
ProcessStartInfo is in the System.Diagnostics namespace - you need to import that namespace at the top of your cs file using a using System.Diagnostics; statement for the compiler to recognise ProcessStartInfo without specifying the namespace explicitly where you use the class.
You could also try System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
To get your local path. For example
//in your imports/using section
using System.IO
using System.Reflection
using System.Diagnostics;
//in your code to execute
Process.start(Path.GetDirectoryName(Aseembly.GetExecutingAssembly().GetName().CodeBase) + "\\program.exe")
There are two cases:
The application was started directly - start up path can be extracted from the command-line.
The application was started indirectly - e.g. from a unit-test, start up path can not be extracted from the command-line, however you can read it from the current directory into a static variable during the start-up (before the user has a chance to change it (e.g. using a file open/save dialog)).