Load file windows forms

Практическое руководство. Загрузка файлов в элемент управления RichTextBox в Windows Forms How to: Load Files into the Windows Forms RichTextBox Control

Элемент управления Windows Forms RichTextBox может отображать обычный текст, обычный текст в Юникоде или файл в формате RTF. The Windows Forms RichTextBox control can display a plain-text, Unicode plain-text, or Rich-Text-Format (RTF) file. Для этого вызовите метод LoadFile . To do so, call the LoadFile method. Метод LoadFile можно также использовать для загрузки данных из потока. You can also use the LoadFile method to load data from a stream. Для получения дополнительной информации см. LoadFile(Stream, RichTextBoxStreamType). For more information, see LoadFile(Stream, RichTextBoxStreamType).

Загрузка файла в элемент управления RichTextBox To load a file into the RichTextBox control

Определить путь к открываемому файлу с помощью компонента OpenFileDialog . Determine the path of the file to be opened using the OpenFileDialog component. Общие сведения см. в разделе Общие сведения о компоненте OpenFileDialog. For an overview, see OpenFileDialog Component Overview.

Вызовите метод LoadFile элемента управления RichTextBox , указав загружаемый файл и при необходимости тип файла. Call the LoadFile method of the RichTextBox control, specifying the file to load and optionally a file type. В следующем примере загружаемый файл берется из свойства OpenFileDialog компонента FileName . In the example below, the file to load is taken from the OpenFileDialog component’s FileName property. Если вы вызываете метод с именем файла в качестве единственного аргумента, предполагается, что тип файла должен быть RTF. If you call the method with a file name as its only argument, the file type will be assumed to be RTF. Чтобы указать другой тип файла, вызовите метод со значением перечисления RichTextBoxStreamType в качестве второго аргумента. To specify another file type, call the method with a value of the RichTextBoxStreamType enumeration as its second argument.

В следующем примере компонент OpenFileDialog отображается при нажатии кнопки. In the example below, the OpenFileDialog component is shown when a button is clicked. Выбранный файл открывается и отображается в элементе управления RichTextBox . The file selected is then opened and displayed in the RichTextBox control. В этом примере предполагается, что форма содержит кнопку btnOpenFile . This example assumes a form has a button, btnOpenFile .

(Visual C#, Visual C++) Поместите следующий код в конструктор формы для регистрации обработчика событий. (Visual C#, Visual C++) Place the following code in the form’s constructor to register the event handler.

Load file windows forms

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

Have problems with Visual Studio 2019, where I have created a solution with 2 projects. The start-up project (# 1) has been created with the Console App (.NETCore) as a base. The second project (# 2) is based on the Windows Forms app (.NET Framework)

Project 1 contains the main logic and calls a procedure in project 2 that will set up a form, take care of specified values ​​and return this via global variables. Both projects do their jobs separately. It is when it comes to the call that errors occur. The call has been adapted as the initial syntax error occurred which has now been corrected so compilation of the solution is error free and without warnings. When executed, there is an interruption

System.IO.FileNotFoundException: ‘Could not load file or assembly ‘System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′. Det går inte att hitta filen.’

This means that it is not possible to track in the program as I wanted. Of course, there are differences in the two projects’ .NET environments that make up for it, but it is not told how I can get hold of the missing file.

Question 1. Does anyone know how to get the file and how it is then incorporated into the environment?

I am not a VB encoder so that with Objects, classes, methods etc. is not something I have immersed myself in. However, I can do so much that I can make it work as regular calls with arguments and so on.

The call itself is simple in itself and I think I got to that with how to send the information. However, I do not find anywhere the values ​​that the parameters should contain.

Call MYform1.Form1_Load(Mysender, Myargs)

Question 2. Does anyone know how to find which values ​​should be included in the Mysender and Myargs parameters

In the log I find this

‘Project20200727.exe’ (CoreCLR: DefaultDomain): Loaded ‘C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.1.6\System.Private.CoreLib.dll’.

‘Project20200727.exe’ (CoreCLR: clrhost): Loaded ‘C:\Users\janne\source\repos\Project20200727\bin\Debug\netcoreapp3.1\Project20200727.dll’. Symbols loaded.

‘Project20200727.exe’ (CoreCLR: clrhost): Loaded ‘C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.1.6\System.Runtime.dll’.

‘Project20200727.exe’ (CoreCLR: clrhost): Loaded ‘C:\Users\janne\source\repos\Project20200727\bin\Debug\netcoreapp3.1\WindowsApp3_20200730.exe’. Symbols loaded.

An unhandled exception of type ‘System.IO.FileNotFoundException’ occurred in Unknown Module.

Читайте также:  Smb client linux gui

Could not load file or assembly ‘System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’. Det går inte att hitta filen.

The program ‘[13828] Project20200727.exe’ has exited with code -1 (0xffffffff).

Windows Form Designer: Could not load file or assembly

Has anyone ever had the issue where trying to «View Designer» on a windows form in Visual Studio .NET causes the error: «Could not load file or assembly…» ?

In this case, the assembly in question was XYZ.dll . I managed to fix this by adding XYZ.dll and all its references to my project’s references (even though my project doesn’t directly depend on them) and rebuilding the whole solution. However, after that, I removed all those references from my project, rebuilt, and it still worked.

One other piece of information is that I use Resharper 2.5. Someone else pointed out that it might be Resharper doing some shadow copying. I’ll look into this next time this happens. Does anyone have a understanding of why this error happens in the first place, and possibly the ‘correct’ way to fix it?

22 Answers 22

We have same problem. Some Form/UserControl classes can not be viewed in designer and Visual Studio causes various exceptions.

There are one typical cause: One of designed component thrown unhandled exception during initialization ( in constructor or in Load event or before ).

Not only for this case, you can run another instance of visual studio, open/create some independent project, go to menu -> Debug -> Attach to process . -> select instance of devenv.exe process with problematic designer. Then press Ctrl+Alt+E, the «Exceptions» windows should be shown. There check «Thrown» in categories of exception.

Now active the visual studio with designer and try view designer. If the exception will be thrown, you will see callstack ( and maybe source code, if the exception was thrown from your code ) and other typical information about thrown exception. This information may be very helpful.

This is an old question that still appears to have no answer, either here or in the wider forum pool, most advice relates to relentless clean>rebuilds or close>clean folders>reopen or restarting the machine. I don’t have a solid answer at present though have done some research into it and thought I might share. Summarily, there is one location into which all designer files are copied when a control or form is designed, another location which old files can exist and a method is described to catch all designer exceptions before the designer can generate the error page.

There appears to be two cases where either an assembly cant be loaded or can’t be found. The first is caused by files failing to copy to designer-required locations, the second is outdated files being left behind.

As mentioned above files can fail to copy when a project fails to directly reference all references required by its referenced references and their references, recursively, down to the framework. This can be alleviated by carefully tracking all references and their dependents, ensuring all are accounted for.

The Visual Studio designer uses a specific location to cache dlls for its use in the designer, isolated from the source /bin folders of the projects:

C:\Documents and Settings\[user_name]\Local Settings\Application Data\Microsoft\VisualStudio\10.0\ProjectAssemblies

C:\Users\[user_name]\AppData\Local\Microsoft\VisualStudio\10.0\ProjectAssemblies

In this location, compiled assemblies are copied to dynamically created folders, one folder per assembly. Checking the assembly version dates on this location, it seems to be quite up to date, being deleted when visual studio exits. All assemblies are copied when a designer is viewed with newly compiled files. A new copy of each assembly is made into this location for each designer, so the location may hold multiple identical copies of each assembly.

One other location exists however where assemblies may be copied, and is a part of the assembly search sequence, apparently ahead of the ProjectAssemblies folder and that is in:

C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE

I have no knowledge of how or when assemblies get copied to this location, but it is not often so what files do arrive here quickly become a source of outdated references. When a designer failed with the ‘Failed to load file or assembly’ error, the version sought by the designer was a version only referenced by the assembly at this location.

This was discovered by using a second Visual Studio instance debugging on the first, with all .net symbols loaded, and all known exceptions breaking on throw as opposed to when unhandled. This allowed the second instance to intercept the handled designer exceptions and reveal that file location. This was the resulting output of the designer error that I used:

Пошаговое руководство. Использование потока данных в приложении Windows Forms Walkthrough: Using Dataflow in a Windows Forms Application

В этом документе демонстрируется способ создания сети блоков потока данных, которые выполняют обработку изображений в приложении Windows Forms. This document demonstrates how to create a network of dataflow blocks that perform image processing in a Windows Forms application.

В этом примере файлы изображения загружаются из указанной папки, из них создается составное изображение, и результат отображается. This example loads image files from the specified folder, creates a composite image, and displays the result. В данном примере для перемещения изображений по сети используется модель потока данных. The example uses the dataflow model to route images through the network. В модели потока данных независимые компоненты программы взаимодействуют друг с другом, отправляя сообщения. In the dataflow model, independent components of a program communicate with one another by sending messages. Когда компонент получает сообщение, он выполняет какое-либо действие и затем передает результат другому компоненту. When a component receives a message, it performs some action and then passes the result to another component. Сравните это с моделью потока управления, в который приложение использует структуры управления, например условные операторы, циклы и т. д., для управления порядком операций в программе. Compare this with the control flow model, in which an application uses control structures, for example, conditional statements, loops, and so on, to control the order of operations in a program.

Читайте также:  Как удалить starting windows

Prerequisites Prerequisites

Прежде чем начать выполнение этого пошагового руководства, ознакомьтесь с документом Поток данных. Read Dataflow before you start this walkthrough.

Библиотека потоков данных TPL (пространство имен System.Threading.Tasks.Dataflow) не поставляется с .NET. The TPL Dataflow Library (the System.Threading.Tasks.Dataflow namespace) is not distributed with .NET. Чтобы установить пространство имен System.Threading.Tasks.Dataflow в Visual Studio, откройте проект, выберите Управление пакетами NuGet в меню Проект и выполните поиск пакета System.Threading.Tasks.Dataflow в Интернете. To install the System.Threading.Tasks.Dataflow namespace in Visual Studio, open your project, choose Manage NuGet Packages from the Project menu, and search online for the System.Threading.Tasks.Dataflow package. Вы также можете установить его, выполнив в .NET Core CLI команду dotnet add package System.Threading.Tasks.Dataflow . Alternatively, to install it using the .NET Core CLI, run dotnet add package System.Threading.Tasks.Dataflow .

Разделы Sections

Это пошаговое руководство содержит следующие разделы: This walkthrough contains the following sections:

Создание приложения Windows Forms Creating the Windows Forms Application

В этом разделе описывается, как создать простое приложение Windows Forms и добавить элементы управления в главную форму. This section describes how to create the basic Windows Forms application and add controls to the main form.

Создание приложения Windows Forms To Create the Windows Forms Application

В Visual Studio создайте проект Приложение Windows Forms на Visual C# или Visual Basic. In Visual Studio, create a Visual C# or Visual Basic Windows Forms Application project. В этом документе проект называется CompositeImages . In this document, the project is named CompositeImages .

В конструкторе форм главной формы Form1.cs (Form1.vb для Visual Basic) добавьте элемент управления ToolStrip. On the form designer for the main form, Form1.cs (Form1.vb for Visual Basic), add a ToolStrip control.

Добавьте элемент управления ToolStripButton к элементу управления ToolStrip. Add a ToolStripButton control to the ToolStrip control. Задайте свойству DisplayStyle значение Text, а свойству Text — Выбрать папку. Set the DisplayStyle property to Text and the Text property to Choose Folder.

Добавьте второй элемент управления ToolStripButton к элементу управления ToolStrip. Add a second ToolStripButton control to the ToolStrip control. Задайте свойству DisplayStyleзначение Text, свойству Text значение Отмена, а свойству Enabled — значение False . Set the DisplayStyle property to Text, the Text property to Cancel, and the Enabled property to False .

Добавьте объект PictureBox на главную форму. Add a PictureBox object to the main form. Задайте для свойства Dock значение Fill. Set the Dock property to Fill.

Создание сети потока данных Creating the Dataflow Network

В этом разделе описывается способ создания сети потока данных, которая выполняет обработку изображений. This section describes how to create the dataflow network that performs image processing.

Создание сети потока данных To Create the Dataflow Network

В своем проекте добавьте ссылку на System.Threading.Tasks.Dataflow.dll. Add a reference to System.Threading.Tasks.Dataflow.dll to your project.

Убедитесь, что Form1.cs (Form1.vb для Visual Basic) содержит следующие операторы using ( Using в Visual Basic). Ensure that Form1.cs (Form1.vb for Visual Basic) contains the following using ( Using in Visual Basic) statements:

Добавьте в класс Form1 следующие данные-члены. Add the following data members to the Form1 class:

Добавьте в класс CreateImageProcessingNetwork метод Form1 . Add the following method, CreateImageProcessingNetwork , to the Form1 class. Этот метод создает сеть обработки изображений. This method creates the image processing network.

Выполните метод LoadBitmaps . Implement the LoadBitmaps method.

Выполните метод CreateCompositeBitmap . Implement the CreateCompositeBitmap method.

Версия метода CreateCompositeBitmap в C# использует указатели для обеспечения эффективной обработки объектов System.Drawing.Bitmap. The C# version of the CreateCompositeBitmap method uses pointers to enable efficient processing of the System.Drawing.Bitmap objects. Поэтому необходимо включить параметр Разрешить небезопасный код в проекте для использования ключевого слова небезопасный. Therefore, you must enable the Allow unsafe code option in your project in order to use the unsafe keyword. Дополнительные сведения о включении небезопасного кода в проекте Visual C# см. в разделе Страница «Сборка» в конструкторе проектов (C#). For more information about how to enable unsafe code in a Visual C# project, see Build Page, Project Designer (C#).

Следующая таблица описывает члены сети. The following table describes the members of the network.

Участник Member Type Type Описание: Description
loadBitmaps TransformBlock Принимает путь папки на входе и создает коллекцию объектов Bitmap на выходе. Takes a folder path as input and produces a collection of Bitmap objects as output.
createCompositeBitmap TransformBlock Принимает коллекцию объектов Bitmap на входе и подает составной точечный рисунок на выход. Takes a collection of Bitmap objects as input and produces a composite bitmap as output.
displayCompositeBitmap ActionBlock Отображает составной точечный рисунок на форме. Displays the composite bitmap on the form.
operationCancelled ActionBlock Отображает изображение, чтобы указать, что операция отменена, и позволяет пользователю выбрать другую папку. Displays an image to indicate that the operation is canceled and enables the user to select another folder.

Для подключения блоков потока данных для формирования сети в этом примере используется метод LinkTo. To connect the dataflow blocks to form a network, this example uses the LinkTo method. Метод LinkTo содержит перегруженную версию, которая принимает объект Predicate , указывающий, допускает или отклоняет блок целевого объекта определенное сообщение. The LinkTo method contains an overloaded version that takes a Predicate object that determines whether the target block accepts or rejects a message. Этот механизм фильтрации позволяет блокам сообщений получать только определенные значения. This filtering mechanism enables message blocks to receive only certain values. В этом примере сеть может разветвляться одним из двух способов. In this example, the network can branch in one of two ways. Основная ветвь загружает изображения с диска, создает составное изображение и отображает его на форме. The main branch loads the images from disk, creates the composite image, and displays that image on the form. Другая ветвь отменяет текущую операцию. The alternate branch cancels the current operation. Объекты Predicate позволяют блокам потоков данных, работающим по основной ветви, перейти к альтернативной ветви путем отклонения определенных сообщений. The Predicate objects enable the dataflow blocks along the main branch to switch to the alternative branch by rejecting certain messages. Например, если пользователь отменяет операцию, блок потока данных createCompositeBitmap выводит null ( Nothing в Visual Basic). For example, if the user cancels the operation, the dataflow block createCompositeBitmap produces null ( Nothing in Visual Basic) as its output. Блок потока данных displayCompositeBitmap отклоняет входные значения null , и поэтому сообщение передается operationCancelled . The dataflow block displayCompositeBitmap rejects null input values, and therefore, the message is offered to operationCancelled . Блок потока данных operationCancelled принимает все сообщения и поэтому отображает изображение, чтобы показать, что операция отменена. The dataflow block operationCancelled accepts all messages and therefore, displays an image to indicate that the operation is canceled.

На следующем рисунке показана сеть обработки изображений: The following illustration shows the image processing network:

Поскольку блоки потоков данных displayCompositeBitmap и operationCancelled работают с интерфейсом пользователя, важно, чтобы эти действия происходили в потоке пользовательского интерфейса. Because the displayCompositeBitmap and operationCancelled dataflow blocks act on the user interface, it is important that these actions occur on the user-interface thread. Для этого в процессе создания каждый из этих объектов предоставляет объект ExecutionDataflowBlockOptions, который содержит свойство TaskScheduler со значением TaskScheduler.FromCurrentSynchronizationContext. To accomplish this, during construction, these objects each provide a ExecutionDataflowBlockOptions object that has the TaskScheduler property set to TaskScheduler.FromCurrentSynchronizationContext. Метод TaskScheduler.FromCurrentSynchronizationContext создает объект TaskScheduler, выполняющий работу в текущем контексте синхронизации. The TaskScheduler.FromCurrentSynchronizationContext method creates a TaskScheduler object that performs work on the current synchronization context. Так как метод CreateImageProcessingNetwork вызывается из обработчика кнопки Выбрать папку, которая выполняется в потоке пользовательского интерфейса, действия для блоков потока данных displayCompositeBitmap и operationCancelled также выполняются в потоке пользовательского интерфейса. Because the CreateImageProcessingNetwork method is called from the handler of the Choose Folder button, which runs on the user-interface thread, the actions for the displayCompositeBitmap and operationCancelled dataflow blocks also run on the user-interface thread.

В этом примере используется общий токен отмены, а не устанавливается свойство CancellationToken, поскольку свойство CancellationToken окончательно отменяет выполнение блока потока данных. This example uses a shared cancellation token instead of setting the CancellationToken property because the CancellationToken property permanently cancels dataflow block execution. Токен отмены в этом примере позволяет повторно использовать те же сети потоков данных несколько раз, даже если пользователь отменил одну или несколько операций. A cancellation token enables this example to reuse the same dataflow network multiple times, even when the user cancels one or more operations. См. пример, который использует CancellationToken, чтобы окончательно отменить выполнение блока потока данных. For an example that uses CancellationToken to permanently cancel the execution of a dataflow block, see How to: Cancel a Dataflow Block.

Подключение сети потока данных к пользовательскому интерфейсу Connecting the Dataflow Network to the User Interface

В этом разделе описывается, как подключить сеть потока данных к интерфейсу пользователя. This section describes how to connect the dataflow network to the user interface. Создание составного изображения и отмена операции инициализируются кнопками Выбрать папку и Отмена. The creation of the composite image and cancellation of the operation are initiated from the Choose Folder and Cancel buttons. Когда пользователь выбирает какую-либо из этих кнопок, соответствующее действие выполняется асинхронно. When the user chooses either of these buttons, the appropriate action is initiated in an asynchronous manner.

Подключение сети потока данных к пользовательскому интерфейсу To Connect the Dataflow Network to the User Interface

В конструкторе форм главной формы создайте обработчик событий для события Click кнопки Выбрать папку. On the form designer for the main form, create an event handler for the Click event for the Choose Folder button.

Реализуйте событие Click кнопки Выбрать папку. Implement the Click event for the Choose Folder button.

В конструкторе форм главной формы создайте обработчик событий для события Click кнопки Отмена. On the form designer for the main form, create an event handler for the Click event for the Cancel button.

Реализуйте событие Click для кнопки Отмена. Implement the Click event for the Cancel button.

Полный пример The Complete Example

В следующем примере приведен полный код для этого руководства. The following example shows the complete code for this walkthrough.

На следующем рисунке показаны типовые выходные данные для общей папки \Sample Pictures. The following illustration shows typical output for the common \Sample Pictures\ folder.

Читайте также:  Firebird для windows server 2019
Оцените статью