Форум программистов, компьютерный форум, киберфорум
C# .NET
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.68/19: Рейтинг темы: голосов - 19, средняя оценка - 4.68
0 / 0 / 1
Регистрация: 08.08.2009
Сообщений: 14

IStorage: Как работать и что за фс в файле?

10.07.2010, 14:26. Показов 3889. Ответов 3
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Как работать с этим интерфейсом на C# и что из себя представляет файловая система внутри файла?

Всё что накопал - это англ.статья на MSDN Library, на там чисто описание методов и свойств класса.
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
10.07.2010, 14:26
Ответы с готовыми решениями:

нужно ли предпринемать какие либо действия что бы изменения в файле global.asa начали работать?
нужно ли предпринемать какие либо действия что бы изменения в файле global.asa начали работать.

Буферный IStorage *
Есть некая функция которая осущестляет чтение из расположенного на диске IStorage, всёчётко, но плохо что storage иногда до 4,5 Гб может...

Как работать с файлами в паскаль? Как сортировать данные в файле?
Не совсем понимаю механик работы с файлами. Банально подключить их могу. Но как выполниь главный вопрос адачи не пойму. Помогите пожалуйста...

3
15 / 15 / 1
Регистрация: 01.07.2010
Сообщений: 33
10.07.2010, 14:45
Цитата Сообщение от Alex217Vish Посмотреть сообщение
Как работать с этим интерфейсом на C# и что из себя представляет файловая система внутри файла?

Всё что накопал - это англ.статья на MSDN Library, на там чисто описание методов и свойств класса.
Это интерфейс COM. Используется для составных документов, например, для файлов MS DOC. Подробнее посмотри CompoundDocuments, OLE и COM. Соответственно работашь с ним из C# так же как с любым COM объектом.
0
0 / 0 / 1
Регистрация: 08.08.2009
Сообщений: 14
10.07.2010, 14:49  [ТС]
Ну а можно небольшой пример хотя бы? Просто раньше никогда ни с COM, ни конкретно с IStorage не работал, а сейчас понадобилось.
0
 Аватар для kirill29
2098 / 1263 / 173
Регистрация: 01.02.2009
Сообщений: 2,842
10.07.2010, 15:32
Вот, посмотри этот пример: http://xtractpro.com/articles/... actor.aspx
И еще:
Introduction

This articles demonstrates the use of IStorage interface in managed C# code based on a simple CHM (MSHelp 1.0) decompiler.

Decompiling CHM (help) files with C#

Recently I came across a very interesting problem related to IStorage interface. I had to be able to manipulate IStorage container from managed code. Since my knowledge of COM is limited, I thought I would simply find a snippet of code using Google. I did hope that the provided example would allow me to Read/Write files from compound storage structures. I discovered a couple of incomplete snippets posted in newsgroups but that was not enough. Not enough for me to be lazy and enjoy my favorite programming technique of CTRL+C, CTRL+V. I had to do some actual work on my own. I needed a wrapper what would allow me to easily access the internal structure of any compound storage object. By the way, for the latest version of this wrapper don't forget to visit here.

According to Microsoft, IStorage interface supports the creation and management of structured storage objects. Structured storage allows hierarchical storage of information within a single file, and is often referred to as "a file system within a file". Yes, it does sound interesting but a bit complicated. How about a real life example?

Well, the most simple and powerful example of compound storage object would be good old CHM files. The compound file implementation of IStorage allows you to create and manage sub-storages and streams within a storage object residing in a compound file object. You can pack your entire collection of help documents, HTML files, images etc. into a single IStorage object to save space and to provide your users with a standard file that can be viewed with your trusted help-viewer. Typically you would use tools provided by Microsoft such as HTML Help Workshop to manipulate a collection of help related information. You can also take a look at Microsoft HTML Help 1.4 SDK to get a complete picture of what is a CHM help file anyway and why you need it.

How about reversed process? HTML Help Workshop supports decompiling as well, but it is a standalone application after all and you can't use it if you want to automate certain processes. Let's say you want to be able to access content from a CHM file in the managed code without the hassle of Microsoft UI. Naturally we need some kind of a wrapper that will simplify READ/WRITE operations for us.



Let's try to access the content of IStorage structure using standard COM interfaces provided to us by Microsoft. Microsoft did not provide us with managed classes to manipulate IStorage objects directly, so we'll have to rely on System.Runtime.InteropServices to import interfaces that well need in our managed code.

Just to give you an idea of what elements are present in our IStorage solution, take a look at the snapshot of Visual Studio Project, above.

We'll organize our collection of classes into a single RelatedObjects.Storage namespace. We'll create a IBaseStorageWrapper class that will help us to enumerate all objects packed into an IStorage file.

Ideally we would like to be able to access any stream in a file separately, so we'll create IStorageWrapper and ITStorageWrapper classes that will inherit from the IBaseStorageWrapper. These classes will help us to handle different types of objects stored in the main compound storage object.

The only difference between ITStorageWrapper and IStorageWrapper is the way they access internally stored objects.

IStorageWrapper is using the StgOpenStorage interface available in Ole32.dll.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Ole32
{
    [DllImport("Ole32.dll")]
    public static extern int StgOpenStorage (
        [MarshalAs(UnmanagedType.LPWStr)] string wcsName,
        IStorage pstgPriority,
        int grfMode,               // access method
 
        IntPtr snbExclude,        // must be NULL
 
        int    reserved,         // reserved
 
        out IStorage storage    // returned storage
 
        );
}
ITStorageWrapper is using the ITStorage.StgOpenStorage available via the ITStorage COM interface.


/
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
// <summary>
 
/// .NET interface wrapper for InfoTech interface for ITStorage COM object
 
/// </summary>
 
[ComImport,
Guid("88CC31DE-27AB-11D0-9DF9-00A0C922E6EC"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
SuppressUnmanagedCodeSecurity]
public interface ITStorage 
{    
    [return:MarshalAs(UnmanagedType.Interface)]
    IStorage StgCreateDocfile([In, 
            MarshalAs(UnmanagedType.BStr)] string pwcsName, 
            int    grfMode, 
            int reserved);
 
    [return:MarshalAs(UnmanagedType.Interface)]
    IStorage StgCreateDocfileOnILockBytes(ILockBytes plkbyt, 
                                int grfMode, int reserved);
 
    int StgIsStorageFile([In, 
         MarshalAs(UnmanagedType.BStr)] string pwcsName);
    int StgIsStorageILockBytes(ILockBytes plkbyt);
 
    [return:MarshalAs(UnmanagedType.Interface)]
    IStorage StgOpenStorage([In, 
                MarshalAs(UnmanagedType.BStr)] string pwcsName, 
                IntPtr pstgPriority,
                [In, MarshalAs(UnmanagedType.U4)] int grfMode, 
                IntPtr snbExclude, 
                [In, MarshalAs(UnmanagedType.U4)] int reserved);
 
    [return:MarshalAs(UnmanagedType.Interface)]
    IStorage StgOpenStorageOnILockBytes(ILockBytes plkbyt, 
                IStorage pStgPriority, 
                int grfMode, 
                IntPtr snbExclude, 
                int reserved);
 
    int StgSetTimes([In, MarshalAs(UnmanagedType.BStr)] string lpszName, 
                    FILETIME pctime, 
                    FILETIME patime, 
                    FILETIME pmtime);
    int    SetControlData(ITS_Control_Data pControlData);
    int    DefaultControlData(ITS_Control_Data ppControlData);
    int    Compact([In, MarshalAs(UnmanagedType.BStr)] string pwcsName, 
                        ECompactionLev iLev);
}
Let's look at the flow of our cute little wrapper by looking at the TEST application included in this project. Our goal in this example is to access content elements stored inside a CHM file. As I mentioned above, a CHM file is a compound storage archive that contains a collection of separate files. We will be using our RelatedObjects.Storage dll (compiled separately) to demonstrate how easy it is to access stream objects stored in IStorage archive from managed code.


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
[STAThread]
static void Main(string[] args)
{
// Create Instance of ITStorageWrapper.
 
// During initialization constructor will process CHM file 
 
// and create collection of file objects stored inside CHM file.
 
ITStorageWrapper iw = new ITStorageWrapper(@"I:\apps\abslog.chm");
 
// Loop through collection of objects stored inside IStorage
 
foreach(IBaseStorageWrapper.FileObjects.FileObject 
                                          fileObject in iw.foCollection)
{
    // Check to make sure we can READ stream of an individual file object
 
    if (fileObject.CanRead)
    {
        // We only want to extract HTM files 
 
        //in this example fileObject is our 
 
        // representation of internal file stored in IStorage
 
        if (fileObject.FileName.EndsWith(".htm"))
        {
            Console.WriteLine("Path: " + fileObject.FilePath);
            Console.WriteLine("File: " + fileObject.FileName);
 
            // FileUrl - is an external reference 
 
            //to the internal object. It allows you to display content 
 
            //of a single file in Internet Explorer
 
            // without extracting content from the archive
 
            Console.WriteLine("Url: " + fileObject.FileUrl);
 
            string fileString = fileObject.ReadFromFile();
            Console.WriteLine("Text: " + fileString);
 
            // Direct Extraction sample
 
            fileObject.Save(@"i:\apps\test1\" + fileObject.FileName);
 
            // Read first and then save later example
 
            StreamWriter sw = File.CreateText(@"i:\apps\" + 
                                     fileObject.FileName);
            sw.WriteLine(fileString);
            sw.Close();
 
            Console.ReadLine();
        }
    }
}
Console.ReadLine();
}
Conclusion

As you can see, this example demonstrates several useful internal file manipulation methods. I'm sure that you could use other methods as well. Our company will continue enhancing some of the functionality to make it even easier to manage IStorage objects. You can visit our site to get latest and greatest version and download updated documentation here.

 Комментарий модератора 
взято с codeproject.com
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
10.07.2010, 15:32
Помогаю со студенческими работами здесь

Текстовые файлы c++. Как работать с текстом в файле?
Здравствуйте, мне нужно через с++ проанализировать информацию, которая находится в файле, как это сделать? Т. е. у меня в файле какой-то...

Как работать с библиотекой, находящейся в файле ресурсов
Я добавил dll в References и… че дальше делать не знаю. Что дальше надо сделать чтоб работать с этим компонентом также как и с другими из...

Посоветуйте что прочитать что бы понять как в Idea работать с Mysql
Если есть хорошии статьи ссылочку плиз

В справке Майкрософт говорится, что чекбоксы могут работать как переключатели, но что-то это не работает
Вот здесь сказано, что если присвоить несколько чекбоксов одной группе, они будут вести себя, как переключатели (Radiobutton), однако,...

как лучше представить информацию в файле, чтобы в дальнейшем было удобнее работать с ним?
Здравствуйте, такой вопрос, как лучше представить информацию в файле, что бы в дальнейшем было удобнее работать с ним? Информацию...


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

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
Новые блоги и статьи
Модель здравосоХранения 6. ESG-повестка и устойчивое развитие; углублённый анализ кадрового бренда
anaschu 31.03.2026
В прикрепленном документе раздумья о том, как можно поменять модель в будущем
10 пpимет, которые всегда сбываются
Maks 31.03.2026
1. Чтобы, наконец, пришла маршрутка, надо закурить. Если сигарета последняя, маршрутка придет еще до второй затяжки даже вопреки расписанию. 2. Нaдоели зима и снег? Не надо переезжать. Достаточно. . .
Перемещение выделенных строк ТЧ из одного документа в другой
Maks 31.03.2026
Реализация из решения ниже выполнена на примере нетипового документа "ВыдачаОборудованияНаСпецтехнику" с единственной табличной частью "ОборудованиеИКомплектующие" разработанного в конфигурации КА2. . . .
Functional First Web Framework Suave
DevAlt 30.03.2026
Sauve. IO Апнулись до NET10. Из зависимостей один пакет, работает одинаково хорошо как в режиме проекта так и в интерактивном режиме. из сложностей - чисто функциональный подход. Решил. . .
Автоматическое создание документа при проведении другого документа
Maks 29.03.2026
Реализация из решения ниже выполнена на нетиповых документах, разработанных в конфигурации КА2. Есть нетиповой документ "ЗаявкаНаРемонтСпецтехники" и нетиповой документ "ПланированиеСпецтехники". В. . .
Настройка движения справочника по регистру сведений
Maks 29.03.2026
Решение ниже реализовано на примере нетипового справочника "ТарифыМобильнойСвязи" разработанного в конфигурации КА2, с целью учета корпоративной мобильной связи в коммерческом предприятии. . . .
Автозаполнение реквизита при выборе элемента справочника
Maks 27.03.2026
Программный код из решения ниже на примере нетипового документа "ЗаявкаНаРемонтСпецтехники" разработанного в конфигурации КА2. При выборе "Спецтехники" (Тип Справочник. Спецтехника), заполняется. . .
Сумматор с применением элементов трёх состояний.
Hrethgir 26.03.2026
Тут. https:/ / fips. ru/ EGD/ ab3c85c8-836d-4866-871b-c2f0c5d77fbc Первый документ красиво выглядит, но без схемы. Это конечно не даёт никаких плюсов автору, но тем не менее. . . всё может быть. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru