Tolpeit Stefan
  • Startseite
  • Portfolio
  • Kontakt
  • Blog
  • Suche
  • Menü
  • Facebook
  • Twitter
  • Xing

Filecaching mit C#

In eigener Sache, Programmierung

Ich habe mich in den letzten Tagen mehr mit Filecaching in C# informiert. Es gibt verschiedenste Bibliotheken um ein Filecaching zu implementieren.

Durch langes Googeln, fand ich folgende Projekte.

BinaryRage

SimpleObjectStore

SqlLite.net PCL

Am einfachsten sind wohl die ersten 2 zu nennen. Beide arbeiten mit wenigen Funktionieren wie z.b. eine UddOrUpdate und Remove/Clear funktionien bei denen ein Objekt übergeben werden kann.

Der SqlLite.net PCL arbeitet wei schon der Name sagt mittels SqlLite und ist daher ein bisschen aufwändiger zu verwenden. SqlLite.net PCL wurde von mir jedoch schlussendlich nicht getestet bzw verwenden, da die Benutzung nicht so einfach war.

Gewinner dieser 3 Bibliotheken war der BinaryRage! Folgender ist einfach zu verwenden und komplexe Datentypen abzuspeichern du diese wieder zu laden z.B.: nach einem App Neustart! Auch läuft das lesen und speichern irsinnig schnell. Teilweise können eine Million Datensätze innerhalb einer Sekunden geschrieben werden.

Standartmäßig schreibt BinaryRage seine Daten asynchron ab. Wollte man nach dem speichern Aufruf direkt die Daten lesen, muss eine zusätzliche Funktion aufgerufen werden.

C#
1
BinaryRage.DB.WaitForCompletion();

Der BinaryRage speicher seine Daten als byte File ab mit der Fileändung odb!

Hingegeben der SimpleObjectStore schreibt seine Daten als Json File ab. DAs heißt das File kann auch zwischen durch mit einem Editor begutachtet werden.

Jedoch gibt es beim speichern von großen Datenmengen (bei ca. 20MB) einen Fehler. Scheint so als ob der verwendete Json Serializer nur eine maximal Größe von 20 MB zulest.

Daher der griff zum BinaryRage!

30. Juni 2015/0 Kommentare/von Tolpeit

Automatic Ravendb3 Backup

In eigener Sache, Programmierung, Webprogrammierung

Because the incremental backup of the Ravendb Backend isn`t working perfektly, I have written a little program to Backup a whole Ravendb(Web) Server with one command.

The program makes a Backup and zip that. You can define in the app.config the fileformat to store.

Check it out on GitHub RavendbBackup on Github

21. Januar 2015/0 Kommentare/von Tolpeit

VisualHg mit Visual Studio 2012

Programmierung, Webprogrammierung, Windows

Erst kürzlich hab ich Windows 8 und in dem Zuge auch Visual Studio 2012 installiert.

Es wurde auch schon öfters berichtet, dass die letzte Visualhg Version 1.1.5 nicht mit Vistual Studio 2012 kompatibel ist. Dem ist es nicht so, es gibt eine Lösung.

Löschen un installieren sie nochmal die VisualHg Version. Sollte dies noch nicht reichen führen sie diesen Code aus:

1
"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv " /setup

nun sollte alles wieder so laufen wie früher

 

 

23. November 2012/0 Kommentare/von Tolpeit

Dynamischer Json Serializer

Programmierung, Webprogrammierung

Hier der Beispielcode für einen dynamischen Json De- Serializer. Das heißt ist ein Feld im Json nicht vorhanden, welcher sich in der Classe aber befindet, werden Trotzdem alle anderen Felder befüllt:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  public static class JsonHelper {
        public static string ToJson<T>(T instance) {
            var serializer = new DataContractJsonSerializer(typeof(T));
            using (var tempStream = new MemoryStream()) {
                serializer.WriteObject(tempStream, instance);
                return Encoding.Default.GetString(tempStream.ToArray());
            }
        }
 
        public static T FromJson<T>(string json) {
            var serializer = new DataContractJsonSerializer(typeof(T));
            using (var tempStream = new MemoryStream(Encoding.Unicode.GetBytes(json))) {
                return (T)serializer.ReadObject(tempStream);
            }
        }
    }

Sollte dieses Problem auftreten:

… cannot be deserialized because the required data members ‚k__BackingField …

Lösung: Setzt auf eure Classe das Attribute [DataContract] und auf euren Properties [DataMember] und das Problem sollte gelöst sein.

1
2
3
4
5
6
7
8
9
10
11
 [Serializable, DataContract]
    public class MyClass{
        [DataMember]
        public int ID { get; set; }
        [DataMember]
        public string Var1 { get; set; }
        [DataMember]
        public string Var2 { get; set; }
        [DataMember]
        public string Var3 { get; set; }
    }

21. August 2012/0 Kommentare/von Tolpeit

TR/Phorpiex 552960 Lösung

Programmierung

Problem: Wenn beim öffnen eines Ordners folgende Warnung des Trojaners TR/Phorpiex 552960 bekommt:

Lösung: Folgende Batch bitte auf beide USB Sticks speichern und laufen lassen.

Drücke bitte die Windows Taste + R Taste und schreibe notepad in das Ausführen Fenster.

Kopiere nun folgenden Text aus der Code-Box in das leere Textdokument

1
2
3
4
5
@echo off
attrib -r -s -h *.* /d /s
del /a/f/q autorun*
rd /s /q 84612795
del %0

  • Wähle Datei –> Speichern unter
  • Dateiname:file.bat
  • Dateityp: Wähle Alle Dateien (*.*)Es sollte nun ungefähr so aussehen
  • Starte die file.bat.

Nun sollten die Ordner wieder da sein. Am besten Daten sichern und Formatieren

23. Januar 2012/0 Kommentare/von Tolpeit

Facebook Connect via Asp.net

Programmierung, Webprogrammierung

Facebook Connect via Asp.net ist eigentlich sehr einfach einzurichten.
Dazu benötigt ihr folgende DLL`s
FacebookSDK

Weiters natürlich eine Facebook App.

Diese könnt ihr hier einrichten Facebook for Developer

Ein kleines Beispiel:

Folgender Code ist um sich einzuloggen mittels Facebook

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<div><code>string</code><code>[] extendedPermissions = </code><code>new</code><code>[] { </code><code>"publish_stream"</code><code>, </code><code>"offline_access"</code> <code>};</code></div>
<div><code>var oauth = </code><code>new</code> <code>FacebookOAuthClient { ClientId = appId };</code></div>
<div><code>var parameters = </code><code>new</code> <code>Dictionary&lt;</code><code>string</code><code>, </code><code>object</code><code>&gt;</code></div>
<div><code> </code><code>{</code></div>
<div><code> </code><code>{ </code><code>"response_type"</code><code>, </code><code>"token"</code> <code>},</code></div>
<div><code> </code><code>{ </code><code>"display"</code><code>, </code><code>"popup"</code> <code>}</code></div>
<div><code> </code><code>};</code></div>
<div><code>if</code> <code>(extendedPermissions != </code><code>null</code> <code>&amp;&amp; extendedPermissions.Length &gt; 0)</code></div>
<div><code>{</code></div>
<div><code> </code><code>var scope = </code><code>new</code> <code>StringBuilder();</code></div>
<div><code> </code><code>scope.Append(</code><code>string</code><code>.Join(</code><code>","</code><code>, extendedPermissions));</code></div>
<div><code> </code><code>parameters[</code><code>"scope"</code><code>] = scope.ToString();</code></div>
<div><code>}</code></div>
<div><code>var loginUrl = oauth.GetLoginUrl(parameters);</code></div>

Um nun abzuprüfen ob ein User eingeloggt ist wird folgender Code verwendet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<div><code>private</code> <code>void</code> <code>webBrowser_Navigated(</code><code>object</code> <code>sender, WebBrowserNavigatedEventArgs e)</code></div>
<div><code>{</code></div>
<div><code> </code><code>FacebookOAuthResult result;</code></div>
<div><code> </code><code>if</code> <code>(FacebookOAuthResult.TryParse(e.Url, </code><code>out</code> <code>result))</code></div>
<div><code> </code><code>{</code></div>
<div><code> </code><code>if</code> <code>(result.IsSuccess)</code></div>
<div><code> </code><code>{</code></div>
<div><code> </code><code>var accesstoken = result.AccessToken;</code></div>
<div><code> </code><code>}</code></div>
<div><code> </code><code>else</code></div>
<div><code> </code><code>{</code></div>
<div><code> </code><code>var errorDescription = result.ErrorDescription;</code></div>
<div><code> </code><code>var errorReason = result.ErrorReason;</code></div>
<div><code> </code><code>}</code></div>
<div><code> </code><code>}</code></div>
<div><code>}</code></div>

Auf der FacebookSDK Seite findet ihr natürlich viele Beispiele.

Viel Spaß mit Facebook und Asp.net

11. Januar 2012/0 Kommentare/von Tolpeit

ffMpeg C# Konvertierungs Problem mit großen Files

Programmierung, Webprogrammierung

Das FFmpeg.exe hat Problem mit Videofiles über 5-6mb Größe. Grund dafür ist, dass die FFmpeg.exe den Application pool aufhängt und seinen Ram verschlingt. Daher musste ich den Code des Prozessaufrufes umbauen. Folgender Code funktioniert auch mit Files weit über 2gb.

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
  ProcessStartInfo oInfo = new ProcessStartInfo(this._ffExe, Parameters);
            oInfo.WorkingDirectory = Path.GetDirectoryName(this._ffExe);
            oInfo.UseShellExecute = false;
            oInfo.CreateNoWindow = true;
            oInfo.RedirectStandardOutput = true;
            oInfo.RedirectStandardError = true;
            using (Process proc = System.Diagnostics.Process.Start(oInfo)) {
                using (StreamReader srOutput = proc.StandardError) {
                    System.Text.StringBuilder output = new System.Text.StringBuilder();
 
                    using (StreamReader objStreamReader = proc.StandardError) {
                        System.Text.StringBuilder sbOutPut = new StringBuilder();
 
                        while (!proc.WaitForExit(1000)) {
                            sbOutPut.Append(objStreamReader.ReadToEnd().ToString());
                        }
 
                        if (proc.ExitCode == 0) {
                            proc.Close();
                            if (objStreamReader != null) {
                                objStreamReader.Close();
                            }
                        } else {
                            proc.Close();
                            if (objStreamReader != null) {
                                objStreamReader.Close();
                            }
                        }
                        return sbOutPut.ToString();
                    }
                }
            }

14. April 2011/0 Kommentare/von Tolpeit

ffMpeg c# get PageInfos and Convert Media File

Programmierung, Webprogrammierung

Folgender Code beinhaltet eine Classe, welche mit Hilfe der ffmpeg.exe die VideoInformationen auslesen kann oder ein Video konvertieren kann.

Code wurde hier gefunden

Die ffmpeg.exe könnt ihr hier downloaden: download

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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
 public class Converter {
      #region Properties
        private string _ffExe;
        public string ffExe {
            get {
                return _ffExe;
            }
            set {
                _ffExe = value;
            }
        }
 
        private string _WorkingPath;
        public string WorkingPath {
            get {
                return _WorkingPath;
            }
            set {
                _WorkingPath = value;
            }
        }
 
        #endregion
 
        #region Constructors
        public Converter() {
            Initialize();
        }
        public Converter(string ffmpegExePath) {
            _ffExe = ffmpegExePath;
            Initialize();
        }
        #endregion
 
        #region Initialization
        private void Initialize() {
            //first make sure we have a value for the ffexe file setting
            if (string.IsNullOrEmpty(_ffExe)) {
                object o = ConfigurationManager.AppSettings["ffmpeg:ExeLocation"];
                if (o == null) {
                    throw new Exception("Could not find the location of the ffmpeg exe file.  The path for ffmpeg.exe " +
                    "can be passed in via a constructor of the ffmpeg class (this class) or by setting in the app.config or web.config file.  " +
                    "in the appsettings section, the correct property name is: ffmpeg:ExeLocation");
                } else {
                    if (string.IsNullOrEmpty(o.ToString())) {
                        throw new Exception("No value was found in the app setting for ffmpeg:ExeLocation");
                    }
                    _ffExe = o.ToString();
                }
            }
 
            //Now see if ffmpeg.exe exists
            string workingpath = GetWorkingFile();
            if (string.IsNullOrEmpty(workingpath)) {
                //ffmpeg doesn't exist at the location stated.
                throw new Exception("Could not find a copy of ffmpeg.exe");
            }
            _ffExe = workingpath;
 
            //now see if we have a temporary place to work
            if (string.IsNullOrEmpty(_WorkingPath)) {
                object o = ConfigurationManager.AppSettings["ffmpeg:WorkingPath"];
                if (o != null) {
                    _WorkingPath = o.ToString();
                } else {
                    _WorkingPath = string.Empty;
                }
            }
        }
 
        private string GetWorkingFile() {
            //try the stated directory
            if (File.Exists(_ffExe)) {
                return _ffExe;
            }
 
            //oops, that didn't work, try the base directory
            if (File.Exists(Path.GetFileName(_ffExe))) {
                return Path.GetFileName(_ffExe);
            }
 
            //well, now we are really unlucky, let's just return null
            return null;
        }
        #endregion
 
        #region Get the File without creating a file lock
        public static System.Drawing.Image LoadImageFromFile(string fileName) {
            System.Drawing.Image theImage = null;
            using (FileStream fileStream = new FileStream(fileName, FileMode.Open,
            FileAccess.Read)) {
                byte[] img;
                img = new byte[fileStream.Length];
                fileStream.Read(img, 0, img.Length);
                fileStream.Close();
                theImage = System.Drawing.Image.FromStream(new MemoryStream(img));
                img = null;
            }
            GC.Collect();
            return theImage;
        }
 
        public static MemoryStream LoadMemoryStreamFromFile(string fileName) {
            MemoryStream ms = null;
            using (FileStream fileStream = new FileStream(fileName, FileMode.Open,
            FileAccess.Read)) {
                byte[] fil;
                fil = new byte[fileStream.Length];
                fileStream.Read(fil, 0, fil.Length);
                fileStream.Close();
                ms = new MemoryStream(fil);
            }
            GC.Collect();
            return ms;
        }
        #endregion
 
        #region Run the process
        private string RunProcess(string Parameters) {
            //create a process info
            ProcessStartInfo oInfo = new ProcessStartInfo(this._ffExe, Parameters);
            oInfo.UseShellExecute = false;
            oInfo.CreateNoWindow = true;
            oInfo.RedirectStandardOutput = true;
            oInfo.RedirectStandardError = true;
 
            //Create the output and streamreader to get the output
            string output = null; StreamReader srOutput = null;
 
            //try the process
            try {
                //run the process
                Process proc = System.Diagnostics.Process.Start(oInfo);
                proc.WaitForExit();
                //get the output
                srOutput = proc.StandardError;
                //now put it in a string
                output = srOutput.ReadToEnd();
 
                proc.Close();
            } catch (Exception) {
                output = string.Empty;
            } finally {
                //now, if we succeded, close out the streamreader
                if (srOutput != null) {
                    srOutput.Close();
                    srOutput.Dispose();
                }
            }
            return output;
        }
        #endregion
 
        #region GetVideoInfo
        public VideoFile GetVideoInfo(MemoryStream inputFile, string Filename) {
            string tempfile = Path.Combine(this.WorkingPath, System.Guid.NewGuid().ToString() + Path.GetExtension(Filename));
            FileStream fs = File.Create(tempfile);
            inputFile.WriteTo(fs);
            fs.Flush();
            fs.Close();
            GC.Collect();
 
            VideoFile vf = null;
            try {
                vf = new VideoFile(tempfile);
            } catch (Exception ex) {
                throw ex;
            }
            GetVideoInfo(vf);
            try {
                File.Delete(tempfile);
            } catch (Exception) {
 
            }
 
            return vf;
        }
        public VideoFile GetVideoInfo(string inputPath) {
            VideoFile vf = null;
            try {
                vf = new VideoFile(inputPath);
            } catch (Exception ex) {
                throw ex;
            }
            GetVideoInfo(vf);
            return vf;
        }
        public void GetVideoInfo(VideoFile input) {
            //set up the parameters for video info
            string Params = string.Format("-i {0}", input.Path);
            string output = RunProcess(Params);
            input.RawInfo = output;
 
            //get duration
            Regex re = new Regex("[D|d]uration:.((\\d|:|\\.)*)");
            Match m = re.Match(input.RawInfo);
 
            if (m.Success) {
                string duration = m.Groups[1].Value;
                string[] timepieces = duration.Split(new char[] { ':', '.' });
                if (timepieces.Length == 4) {
                    input.Duration = new TimeSpan(0, Convert.ToInt16(timepieces[0]), Convert.ToInt16(timepieces[1]), Convert.ToInt16(timepieces[2]), Convert.ToInt16(timepieces[3]));
                }
            }
 
            //get audio bit rate
            re = new Regex("[B|b]itrate:.((\\d|:)*)");
            m = re.Match(input.RawInfo);
            double kb = 0.0;
            if (m.Success) {
                Double.TryParse(m.Groups[1].Value, out kb);
            }
            input.BitRate = kb;
 
            //get the audio format
            re = new Regex("[A|a]udio:.*");
            m = re.Match(input.RawInfo);
            if (m.Success) {
                input.AudioFormat = m.Value;
            }
 
            //get the video format
            re = new Regex("[V|v]ideo:.*");
            m = re.Match(input.RawInfo);
            if (m.Success) {
                input.VideoFormat = m.Value;
            }
 
            //get the video format
            re = new Regex("(\\d{2,3})x(\\d{2,3})");
            m = re.Match(input.RawInfo);
            if (m.Success) {
                int width = 0; int height = 0;
                int.TryParse(m.Groups[1].Value, out width);
                int.TryParse(m.Groups[2].Value, out height);
                input.Width = width;
                input.Height = height;
            }
            input.infoGathered = true;
        }
        #endregion
 
        #region Convert to FLV
        public OutputPackage ConvertToFLV(MemoryStream inputFile, string Filename) {
            string tempfile = Path.Combine(this.WorkingPath, System.Guid.NewGuid().ToString() + Path.GetExtension(Filename));
            FileStream fs = File.Create(tempfile);
            inputFile.WriteTo(fs);
            fs.Flush();
            fs.Close();
            GC.Collect();
 
            VideoFile vf = null;
            try {
                vf = new VideoFile(tempfile);
            } catch (Exception ex) {
                throw ex;
            }
 
            OutputPackage oo = ConvertToFLV(vf);
 
            try {
                File.Delete(tempfile);
            } catch (Exception) {
 
            }
 
            return oo;
        }
        public OutputPackage ConvertToFLV(string inputPath) {
            VideoFile vf = null;
            try {
                vf = new VideoFile(inputPath);
            } catch (Exception ex) {
                throw ex;
            }
 
            OutputPackage oo = ConvertToFLV(vf);
            return oo;
        }
        public OutputPackage ConvertToFLV(VideoFile input) {
            if (!input.infoGathered) {
                GetVideoInfo(input);
            }
            OutputPackage ou = new OutputPackage();
 
            //set up the parameters for getting a previewimage
            string filename = System.Guid.NewGuid().ToString() + ".jpg";
            int secs;
 
            //divide the duration in 3 to get a preview image in the middle of the clip
            //instead of a black image from the beginning.
            secs = (int)Math.Round(TimeSpan.FromTicks(input.Duration.Ticks / 3).TotalSeconds, 0);
 
            string finalpath = Path.Combine(this.WorkingPath, filename);
            string Params = string.Format("-i {0} {1} -vcodec mjpeg -ss {2} -vframes 1 -an -f rawvideo", input.Path, finalpath, secs);
            string output = RunProcess(Params);
 
            ou.RawOutput = output;
 
            if (File.Exists(finalpath)) {
                ou.PreviewImage = LoadImageFromFile(finalpath);
                try {
                    File.Delete(finalpath);
                } catch (Exception) { }
            } else { //try running again at frame 1 to get something
                Params = string.Format("-i {0} {1} -vcodec mjpeg -ss {2} -vframes 1 -an -f rawvideo", input.Path, finalpath, 1);
                output = RunProcess(Params);
 
                ou.RawOutput = output;
 
                if (File.Exists(finalpath)) {
                    ou.PreviewImage = LoadImageFromFile(finalpath);
                    try {
                        File.Delete(finalpath);
                    } catch (Exception) { }
                }
            }
 
            finalpath = Path.Combine(this.WorkingPath, filename);
            filename = System.Guid.NewGuid().ToString() + ".flv";
            Params = string.Format("-i {0} -y -ar 22050 -ab 64 -f flv {1}", input.Path, finalpath);
            output = RunProcess(Params);
 
            if (File.Exists(finalpath)) {
                ou.VideoStream = LoadMemoryStreamFromFile(finalpath);
                try {
                    File.Delete(finalpath);
                } catch (Exception) { }
            }
            return ou;
        }
        #endregion
    }
 
    public class VideoFile {
        #region Properties
        private string _Path;
        public string Path {
            get {
                return _Path;
            }
            set {
                _Path = value;
            }
        }
 
        public TimeSpan Duration { get; set; }
        public double BitRate { get; set; }
        public string AudioFormat { get; set; }
        public string VideoFormat { get; set; }
        public int Height { get; set; }
        public int Width { get; set; }
        public string RawInfo { get; set; }
        public bool infoGathered { get; set; }
        #endregion
 
        #region Constructors
        public VideoFile(string path) {
            _Path = path;
            Initialize();
        }
        #endregion
 
        #region Initialization
        private void Initialize() {
            this.infoGathered = false;
            //first make sure we have a value for the video file setting
            if (string.IsNullOrEmpty(_Path)) {
                throw new Exception("Could not find the location of the video file");
            }
 
            //Now see if the video file exists
            if (!File.Exists(_Path)) {
                throw new Exception("The video file " + _Path + " does not exist.");
            }
        }
        #endregion
    }
 
    public class OutputPackage{
        public MemoryStream VideoStream { get; set; } public System.Drawing.Image PreviewImage { get; set; } public string RawOutput { get; set; } public bool Success { get; set; }
    }
 
}

14. April 2011/0 Kommentare/von Tolpeit

c# Datei Informationen auslesen

Programmierung, Webprogrammierung

Folgender Code hilft Ihnen alle Metadaten einer Datei auszulesen. Bei Videos sogar Duration/Länge und  Bitrate.

Diese Funktioniert für alle Dateientypen wie z.b. txt, mp4, gif, jpg, mp3 usw.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  public static class FileInfoExtensions {
        public static Dictionary&lt;string, string&gt; GetDetails(this FileInfo fi) {
            Dictionary&lt;string, string&gt; ret = new Dictionary&lt;string, string&gt;();
            var shl = (Shell)Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
            //Shell shl = new ShellClass();
            Folder folder = shl.NameSpace(fi.DirectoryName);
            FolderItem item = folder.ParseName(fi.Name);
 
            for (int i = 0; i &lt; 150; i++) {
                string dtlDesc = folder.GetDetailsOf(null, i);
                string dtlVal = folder.GetDetailsOf(item, i);
 
                if (dtlVal == null || dtlVal == "")
                    continue;
 
                ret.Add(dtlDesc, dtlVal);
            }
            return ret;
        }
    }

Hier muss lediglich eine Referenz zu der COM Shell32.dll hinzugefügt werden.

12. April 2011/0 Kommentare/von Tolpeit

Itext merge pdf

Programmierung, Webprogrammierung

Here is the code to merge a pdf file in 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
namespace MergePDF {
        public class MergeEx {
            #region Fields
            private string sourcefolder;
            private string destinationfile;
            private IList fileList = new ArrayList();
            #endregion
 
            #region Public Methods
            ///
            /// Add a new file, together with a given docname to
            /// the fileList and namelist collection
            ///
            ///
            public void AddFile(string pathnname) {
                fileList.Add(pathnname);
            }
 
            ///
            /// Generate the merged PDF
            ///
            public void Execute() {
                MergeDocs();
            }
            #endregion
 
            #region Private Methods
            ///
            /// Merges the Docs and renders the destinationFile
            ///
            ///
            private void MergeDocs() {
 
                //Step 1: Create a Docuement-Object
                Document document = new Document();
                try {
                    //Step 2: we create a writer that listens to the document
                    PdfWriter writer = PdfWriter.GetInstance(document,
           new FileStream(destinationfile, FileMode.Create));
                    //Step 3: Open the document
                    document.Open();
 
                    PdfContentByte cb = writer.DirectContent;
                    PdfImportedPage page;
 
                    int n = 0;
                    int rotation = 0;
 
                    //Loops for each file that has been listed
                    foreach (string filename in fileList) {
                        //The current file path
                        string filePath = sourcefolder + filename;
 
                        // we create a reader for the document
                        PdfReader reader = new PdfReader(filePath);
 
                        //Gets the number of pages to process
                        n = reader.NumberOfPages;
 
                        int i = 0;
                        while (i &lt; n) {
                            i++;
                            document.SetPageSize(reader.GetPageSizeWithRotation(1));
                            document.NewPage();
 
                            //Insert to Destination on the first page
                            if (i == 1) {
                                Chunk fileRef = new Chunk(" ");
                                fileRef.SetLocalDestination(filename);
                                document.Add(fileRef);
                            }
 
                            page = writer.GetImportedPage(reader, i);
                            rotation = reader.GetPageRotation(i);
                            if (rotation == 90 || rotation == 270) {
                                cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                            } else {
                                cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                            }
                        }
                    }
                } catch (Exception e) { throw e; } finally { document.Close(); }
            }
            #endregion
 
            #region Properties
            ///
            /// Gets or Sets the SourceFolder
            ///
            public string SourceFolder {
                get { return sourcefolder; }
                set { sourcefolder = value; }
            }
 
            ///
            /// Gets or Sets the DestinationFile
            ///
            public string DestinationFile {
                get { return destinationfile; }
                set { destinationfile = value; }
            }
            #endregion
        }
 
    }

So you can call the merge function in the context.

1
2
3
4
5
6
7
string sourcePath = @"D:\Pdf\";
                MergeEx objMergeEx = new MergeEx();
                objMergeEx.SourceFolder = sourcePath;
                objMergeEx.DestinationFile = sourcePath + "Mergedfile.pdf";
                objMergeEx.AddFile("parsetest.pdf");
                objMergeEx.AddFile(@"regions\" + "eisacktal.pdf");
                objMergeEx.Execute();

download: itext

20. September 2010/1 Kommentar/von Tolpeit
Seite 1 von 212

Letzte Artikel

  • Filecaching mit C#
  • Automatic Ravendb3 Backup
  • Form als Json serialisieren und mittels Jquery Ajax posten
  • Javascript – Herausfinden ob der userAgent ein Iphone oder Ipad ist
  • Füge Git zu Windows 7 Path hinzu
  • Xbox One flashen – Modchip
  • Flugsportzentrum Tirol im Neuem Design
  • The remote server returned an error: (411) Length Required
  • Facebook Freunde einladen alle Freunde markieren
  • Umbraco 6.0 mit MVC und Razor verwenden

Letzte Projekte

  • Physio & Rehacenter Bruneck28. Juli 2019 - 21:06

    Programmierung der Website www.physio-bruneck.com

  • Karosserie Leitner28. Juli 2019 - 21:05

    Programmierung der Website www.karosserie-leitner.com

  • Hotel Lindenwirt2. Mai 2019 - 21:40

    Programmierung der Website www.hotel-lindenwirt.de im Bayrischen Wald.

Kategorien

  • Allgemein
  • In eigener Sache
  • Javascript
  • Kaufberatung
  • Konsolen
  • Programmierung
  • Spiele
  • Technik
  • Tools
  • Treiber
  • Webprogrammierung
  • Windows
  • XBox 360

Links

  • Datenschutz
  • Flightplanning24 – Metar Taf Webcams
  • Impressum

Seiten

  • Portfolio
  • Stefan Tolpeit
  • Kontakt
  • Blog

Suchen

Kommentare

  • Guruprasad bei NopCommerce multi domain with seperate languages support
  • Tolpeit bei NopCommerce multi domain with seperate languages support
  • Guruprasad bei NopCommerce multi domain with seperate languages support
  • Tolpeit bei NopCommerce multi domain with seperate languages support
  • Guruprasad bei NopCommerce multi domain with seperate languages support
© Copyright - Tolpeit Stefan P.IVA: 02832950212 - Enfold Theme by Kriesi
Nach oben scrollen
tolpeit.it verwendet Cookies von Dritten um Ihnen den bestmöglichen Service zu bieten. Wenn Sie weiterhin auf diesen Seiten surfen, stimmen Sie der Cookie-Nutzung zu. OKReject Mehr Erfahren
Cookies & Privacy