Форум программистов, компьютерный форум, киберфорум
C++/CLI Windows Forms
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.73/11: Рейтинг темы: голосов - 11, средняя оценка - 4.73
45 / 6 / 1
Регистрация: 20.08.2012
Сообщений: 200

Программа возвращающая лист папок и лист файлов по заданному пути

26.12.2012, 20:29. Показов 2122. Ответов 9
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Сначала объявляем структуру возвращаемую функцией
C++
1
2
3
4
5
ref struct dirsfiles
{ 
    array<DirectoryInfo^>^ list_dirs;
    array<FileInfo^>^ list_files;
};
сама функция
C++
1
2
3
4
5
6
7
8
9
dirsfiles getdirsfiles(String^ dirPath) // dirPath - входной путь
{
   System::IO::DirectoryInfo ^ dirs;
   dirs = gcnew System::IO::DirectoryInfo(dirPath);
   dirsfiles ff; // list folders and list files
   ff.list_dirs = dirs->GetDirectories(); // заполняем поля структуры
   ff.list_files = dirs->GetFiles();
   return ff;
}
получаю ошибку на строке 'return ff;'
error C2440: 'return' : cannot convert from 'dirsfiles' to 'dirsfiles'

Подскажите в чем моя ошибка?

Добавлено через 14 минут
сообщение отредактировано неверно, этот код на C++, а не на С#
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
26.12.2012, 20:29
Ответы с готовыми решениями:

Пользовательская функция, возвращающая массив на лист
Доброго времени суток! Есть задача: написать пользовательскую функцию, которая принимает массив с листа, обсчитывает его и возвращает...

Libre Calc, выборочное заполнение ячеек в Лист 2 из Лист 1 по команде
Может кто поможет... Есть заранее сформированный список Людей и их данных (Лист 1), необходимо в Листе 2 реализовать автозаполнение ячеек...

Как создать новый лист в книге со ссылкой на предыдущий лист?
Добрый день. Есть реестр учета спецтехники. Его заполняет диспетчер каждый день. т.е. каждый день копирует форму на новый лист и потом...

9
873 / 771 / 173
Регистрация: 11.01.2012
Сообщений: 1,942
26.12.2012, 21:19
C++
1
2
3
4
5
6
7
8
9
dirsfiles^ getdirsfiles(String^ dirPath) // dirPath - входной путь
{
   System::IO::DirectoryInfo ^ dirs;
   dirs = gcnew System::IO::DirectoryInfo(dirPath);
   dirsfiles^ ff = gcnew dirsfiles(); // list folders and list files
   ff->list_dirs = dirs->GetDirectories(); // заполняем поля структуры
   ff->list_files = dirs->GetFiles();
   return ff;
}
0
45 / 6 / 1
Регистрация: 20.08.2012
Сообщений: 200
26.12.2012, 21:27  [ТС]
так тоже не работает:
error C2440: 'return' : cannot convert from 'dirsfiles' to 'dirsfiles ^'
0
873 / 771 / 173
Регистрация: 11.01.2012
Сообщений: 1,942
26.12.2012, 21:41
В какой строке ошибка ? Хотя бы ту строку покажите .
0
45 / 6 / 1
Регистрация: 20.08.2012
Сообщений: 200
26.12.2012, 21:53  [ТС]
как и прежде в 9 return ff;

Но вот так

C++
1
2
3
4
5
6
7
8
9
10
void comboBox1_SelectedIndexChanged(System::Object^  sender, System::EventArgs^  e)
{
    listBox1->BeginUpdate();
    System::String^ dirPath = comboBox1->Text;
    array<DirectoryInfo^>^ listdirs = listdir(dirPath);
    array<FileInfo^>^ listfiles = listfile(dirPath);
    listBox1->Items->Clear(); listBox1->Items->AddRange(listdirs);
    listBox2->Items->Clear(); listBox2->Items->AddRange(listfiles);
    listBox1->EndUpdate();
}
все работает, но мне нужна именно функция

Добавлено через 10 минут
Вот весь код
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include "stdafx.h"
#using <System.Data.dll>
#using <System.Windows.Forms.dll>
#using <System.dll>
#using <System.Drawing.dll>
 
using namespace System;
using namespace System::Drawing;
using namespace System::Collections;
using namespace System::ComponentModel;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::IO; 
 
ref struct dirsfiles
{ 
    array<DirectoryInfo^>^ list_dirs;   
    array<FileInfo^>^ list_files;   
};
 
public ref class Form1: public System::Windows::Forms::Form
{
private:
   System::Windows::Forms::ComboBox^ comboBox1;
   System::Windows::Forms::ListBox^ listBox1;
   System::Windows::Forms::ListBox^ listBox2;
   System::ComponentModel::Container^ components;
 
public:
   Form1()
   {
      InitializeComponent();
   }
 
public:
   ~Form1()
   {
      if ( components != nullptr )
      {
         delete components;
      }
   }
 
private:
   void InitializeComponent()
   {
      this->components = gcnew System::ComponentModel::Container;
 
      this->comboBox1 = gcnew System::Windows::Forms::ComboBox;
      array<Object^>^ objectArray = {"C:\\","D:\\","L:\\"};
      comboBox1->Items->AddRange( objectArray );
      comboBox1->SelectedIndex = 1;
      comboBox1->Location = System::Drawing::Point( 1, 3 );
      comboBox1->Size = System::Drawing::Size(160, 10);
      this->comboBox1->SelectedIndexChanged += gcnew System::EventHandler(this, &Form1::comboBox1_SelectedIndexChanged);
 
      this->listBox1 = gcnew System::Windows::Forms::ListBox;
      listBox1->Size = System::Drawing::Size( 160, 200 );
      listBox1->Location = System::Drawing::Point( 1, 25 );
     this->listBox1->Click += gcnew System::EventHandler( this, &Form1::listBox1_Click );
      
      this->listBox2 = gcnew System::Windows::Forms::ListBox;
      listBox2->Size = System::Drawing::Size( 160, 400 );
      listBox2->Location = System::Drawing::Point( 1, 225 );
 
      array<System::Windows::Forms::Control^>^ controlsArray = {this->comboBox1, this->listBox1, this->listBox2};
      this->Controls->AddRange( controlsArray );
      this->Text = "ViewRaw";
      this->StartPosition = FormStartPosition::Manual;
      this->Left = 1430; this->Top = 10; this->Width = 170; this->Height = 647;
   }
   array<DirectoryInfo^>^ listdir(String^ dirPath)
    {
        System::IO::DirectoryInfo ^ dirs;
        dirs = gcnew System::IO::DirectoryInfo(dirPath);
        array<DirectoryInfo^>^ listdirs = dirs->GetDirectories();
        return listdirs;
    }
   array<FileInfo^>^ listfile(String^ dirPath)
    {
        System::IO::DirectoryInfo ^ dirs;
        dirs = gcnew System::IO::DirectoryInfo(dirPath);
        array<FileInfo^>^ listfiles = dirs->GetFiles();
        return listfiles;
    }
 
   dirsfiles^ getdirsfiles(String^ dirPath)
   {
       System::IO::DirectoryInfo ^ dirs;
       dirs = gcnew System::IO::DirectoryInfo(dirPath);
       dirsfiles ff; // list folders and list files
       ff.list_dirs = dirs->GetDirectories(); 
       ff.list_files = dirs->GetFiles(); 
       return ff;
   }
 
   void comboBox1_SelectedIndexChanged(System::Object^  sender, System::EventArgs^  e)
   {
        listBox1->BeginUpdate();
        System::String^ dirPath = comboBox1->Text;
        array<DirectoryInfo^>^ listdirs = listdir(dirPath);
        array<FileInfo^>^ listfiles = listfile(dirPath);
        listBox1->Items->Clear(); listBox1->Items->AddRange(listdirs);
        listBox2->Items->Clear(); listBox2->Items->AddRange(listfiles);
        listBox1->EndUpdate();
   }
   void listBox1_Click( Object^ sender, System::EventArgs^ e)
   {
       int a = 0;
       String^ it = this->listBox1->Items[this->listBox1->SelectedIndex]->ToString();
   }
 
};
[STAThread]
int main()
{
   Application::Run( gcnew Form1 );
}
0
873 / 771 / 173
Регистрация: 11.01.2012
Сообщений: 1,942
26.12.2012, 21:56
строка 91 не исправили на
C++
1
dirsfiles^ ff = gcnew dirsfiles(); // list folders and list files
0
45 / 6 / 1
Регистрация: 20.08.2012
Сообщений: 200
26.12.2012, 22:37  [ТС]
Вот так вроде заработало, т.е. пока не ругается
C++
1
2
3
4
5
6
7
8
9
   dirsfiles^ getdirsfiles(String^ dirPath)
   {
       System::IO::DirectoryInfo ^ dirs;
       dirs = gcnew System::IO::DirectoryInfo(dirPath);
       dirsfiles^ ff; // list folders and list files <<<<<<<<<<<<<<<<<< ^^^^^
       ff->list_dirs = dirs->GetDirectories(); 
       ff->list_files = dirs->GetFiles(); 
       return ff;
   }
Добавлено через 4 минуты
MrCold, Вы не представляете сколько крови эта ерунда у меня выпила и это только начало
Мне надо написать мини эксплорер


Добавлено через 29 минут
Проблема все же осталась на строчке 140
0
873 / 771 / 173
Регистрация: 11.01.2012
Сообщений: 1,942
26.12.2012, 22:48
Повторяю
Цитата Сообщение от MrCold Посмотреть сообщение
dirsfiles^ ff = gcnew dirsfiles();
Память надо выделить .
1
45 / 6 / 1
Регистрация: 20.08.2012
Сообщений: 200
27.12.2012, 19:29  [ТС]
MrCold!! главное не пропадай никуда, иначе мне крышка

Добавлено через 20 часов 35 минут
Разбросал программу на модули. Для удобства привожу их в картинках



Мне здесь не нравится что я дважды определяю структуру dirsfiles в tools_miniexp.h и tools_miniexp.cpp
а иначе компиляция не проходит
также дважды вынужден вводить
using namespace System;
using namespace System::IO;
Наверное так как я делать не правильно? А как надо?

Теперь надо написать функцию ff = get_folders_and_files(C, list_folders_of_listBox1, SelectedIndex);
в клике на листбоксе1
Она должна возвращать два списка папок и файлов, а получать: диск (С:\), текущий list_folders_of_listBox1 и выбранный (нажатый) SelectedIndex на листбоксе1. Как получить list_folders_of_listBox1? В какой массив?
array<String^>^ strdirs = this->listBox1->Items[this->listBox1->SelectedIndex]->ToString(); - это только для одного индекса, а как для всех индексов?
На рис ниже приведен вариант возврата функцией get_folders_and_files листа папок (они уже иерархированы и добавлены пробелы)
Название: 784df7750c9b.png
Просмотров: 72

Размер: 1.7 Кб
Все эти процедуры лучше делать видимо со стрингами и в конце конвертировать их в типы структуры dirsfiles. Так я и не нашел функцию конвертирующую array<String^>^ в array<DirectoryInfo^>^

На всякий случай весь код

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//miniexp.cpp
#include "stdafx.h"
#include "tools_miniexp.h"
 
public ref class Form1: public System::Windows::Forms::Form
{
private:
   System::Windows::Forms::ComboBox^ comboBox1;
   System::Windows::Forms::ListBox^ listBox1;
   System::Windows::Forms::ListBox^ listBox2;
   System::ComponentModel::Container^ components;
 
public:
   Form1()
   {
      InitializeComponent();
   }
 
public:
   ~Form1()
   {
      if ( components != nullptr )
      {
         delete components;
      }
   }
 
private:
   void InitializeComponent()
   {
      this->components = gcnew System::ComponentModel::Container;
 
      this->comboBox1 = gcnew System::Windows::Forms::ComboBox;
      array<Object^>^ objectArray = {"C:\\","D:\\","L:\\"};
      comboBox1->Items->AddRange( objectArray );
      comboBox1->SelectedIndex = 1;
      comboBox1->Location = System::Drawing::Point( 1, 3 );
      comboBox1->Size = System::Drawing::Size(160, 10);
      this->comboBox1->SelectedIndexChanged += gcnew System::EventHandler(this, &Form1::comboBox1_SelectedIndexChanged);
 
      this->listBox1 = gcnew System::Windows::Forms::ListBox;
      listBox1->Size = System::Drawing::Size( 160, 200 );
      listBox1->Location = System::Drawing::Point( 1, 25 );
      
      this->listBox1->Click += gcnew System::EventHandler( this, &Form1::listBox1_Click );
      
      this->listBox2 = gcnew System::Windows::Forms::ListBox;
      listBox2->Size = System::Drawing::Size( 160, 400 );
      listBox2->Location = System::Drawing::Point( 1, 225 );
 
      array<System::Windows::Forms::Control^>^ controlsArray = {this->comboBox1, this->listBox1, this->listBox2};
      this->Controls->AddRange( controlsArray );
      this->Text = "ViewRaw";
      this->StartPosition = FormStartPosition::Manual;
      this->Left = 1430; this->Top = 10; this->Width = 170; this->Height = 647;
   }
 
   void comboBox1_SelectedIndexChanged(System::Object^, System::EventArgs^)
   {
        listBox1->BeginUpdate();
        System::String^ dirPath = comboBox1->Text;
        listBox1->Items->Clear(); listBox1->Items->AddRange(getdirsfiles(dirPath)->list_dirs);
        listBox2->Items->Clear(); listBox2->Items->AddRange(getdirsfiles(dirPath)->list_files);
        listBox1->EndUpdate();
   }
   void listBox1_Click(Object^ sender, System::EventArgs^ e)
   {
       String^ C = this->comboBox1->Text;
       int SelectedIndex = this->listBox1->SelectedIndex;
       dirsfiles^ ff = gcnew dirsfiles(); // list folders and list files
       ff = get_folders_and_files(C, list_folders_of_listBox1, SelectedIndex);
   }
};
[STAThread]
int main()
{
   Application::Run( gcnew Form1 );
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//tools_miniexp.h
#include "stdafx.h"
#using <System.Data.dll>
#using <System.Windows.Forms.dll>
#using <System.dll>
#using <System.Drawing.dll>
 
using namespace System;
using namespace System::Drawing;
using namespace System::Collections;
using namespace System::ComponentModel;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::IO; 
 
ref struct dirsfiles
{ 
    array<DirectoryInfo^>^ list_dirs;
    array<FileInfo^>^ list_files;
};
 
dirsfiles^ getdirsfiles(String^);
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//tools_miniexp.cpp
#include "stdafx.h"
 
using namespace System;
using namespace System::IO; 
 
ref struct dirsfiles
{ 
    array<DirectoryInfo^>^ list_dirs;
    array<FileInfo^>^ list_files;
};
 
dirsfiles^ getdirsfiles(String^ dirPath)
{
   System::IO::DirectoryInfo ^ dirs;
   dirs = gcnew System::IO::DirectoryInfo(dirPath);
   dirsfiles^ ff = gcnew dirsfiles(); // list folders and list files
   ff->list_dirs = dirs->GetDirectories();
   ff->list_files = dirs->GetFiles();
   return ff;
}
0
Почетный модератор
 Аватар для Памирыч
23249 / 9161 / 1084
Регистрация: 11.04.2010
Сообщений: 11,014
27.12.2012, 20:00
tur9, теги не забываем. Картинки прикрепляйте к посту
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
27.12.2012, 20:00
Помогаю со студенческими работами здесь

Перенести на новый лист строки с определенным именем, и переименовать лист
Приветствую уважаемых форумчан! У меня есть книга в excel (питание в университетской столовой), хотелось бы сделать так, чтобы данные из...

Новый лист с таким же названием но в конце порядковый номер если лист уже существует
Здравствуйте. Нужна маленькая помощь. Делаю копию листа , название беру из ячейки этого же листа. Но бывают такие случаи когда...

Копирование данных с листа 1 на лист 3 при условии в лист 2
Помогите пожалуйста пересмотрел примеры решения на форуме. но не могу найти нужное. есть 3 листа с данными. на лист №1 идет прайс...

Сериализация класса содержащий лист и лист листов
Всем привет. Пытаюсь сериализовать класс содержащий лист и лист листов: public class Archive { public static...

Поиск ячейки с Лист 1, копирование на Лист 2
Доброго времени суток! Не силен в VBA, поэтому прошу помощи. Имеется файл, в котором есть чередующиеся столбцы: время, значение....


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
10
Ответ Создать тему
Новые блоги и статьи
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит переходные токи и напряжения на элементах схемы. . . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru