Example #1
0
        private static void UnZip(string zipFile, string folderPath)
        //flags above used to configure copy options
        //4 – Do not display a progress dialog box.
        //8 – Give the file being operated on a new name in a move, copy, or rename operation if a file with the target name already exists.
        //16 – Respond with “Yes to All” for any dialog box that is displayed.
        //64 – Preserve undo information, if possible.
        //128 – Perform the operation on files only if a wildcard file name(*.*) is specified.
        //256 – Display a progress dialog box but do not show the file names.
        //512 – Do not confirm the creation of a new directory if the operation requires one to be created.
        //1024 – Do not display a user interface if an error occurs.
        //2048 – Version 4.71. Do not copy the security attributes of the file.
        //4096 – Only operate in the local directory.Do not operate recursively into subdirectories.
        //8192 – Version 5.0. Do not copy connected files as a group. Only copy the specified files.
        {
            if (!File.Exists(zipFile))
            {
                throw new FileNotFoundException();
            }

            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            Shell32.Shell  objShell          = new Shell32.Shell();
            Shell32.Folder destinationFolder = objShell.NameSpace(folderPath);
            Shell32.Folder sourceFile        = objShell.NameSpace(zipFile);
            foreach (var file in sourceFile.Items())
            {
                destinationFolder.CopyHere(file, 16);
            }
        }
Example #2
0
        /*
         *
         * Metoda wyodrębniania plików z formatu .zip.
         */
        public static void UnZip(string zipFile, string folderPath)
        {
            Shell32.Shell  objShell          = new Shell32.Shell();
            Shell32.Folder destinationFolder = objShell.NameSpace(folderPath);
            Shell32.Folder sourceFile        = objShell.NameSpace(zipFile);

            foreach (var file in sourceFile.Items())
            {
                destinationFolder.CopyHere(file, 4 | 16);
            }
        }
        public static void UnZip(string zipFile, string folderPath)
        {
            if (!Directory.Exists(folderPath))
                Directory.CreateDirectory(folderPath);

            Shell32.Shell objShell = new Shell32.Shell();
            Shell32.Folder destinationFolder = objShell.NameSpace(folderPath);
            Shell32.Folder sourceFile = objShell.NameSpace(zipFile);

            foreach (var file in sourceFile.Items())
            {
                destinationFolder.CopyHere(file, 4 | 16);
            }
        }
Example #4
0
        /// <summary>
        /// Get duration(ms) of audio or vedio by Shell32.dll
        /// </summary>
        /// <param name="filePath">audio/vedio's path</param>
        /// <returns>Duration in original format, duration in milliseconds</returns>
        /// <remarks>return value from Shell32.dll is in format of: "00:10:16"</remarks>
        public override Tuple <string, long> GetDuration(string filePath)
        {
            try
            {
                string dir = Path.GetDirectoryName(filePath);

                // From Add Reference --> COM
                Shell32.Shell      shell      = new Shell32.Shell();
                Shell32.Folder     folder     = shell.NameSpace(dir);
                Shell32.FolderItem folderitem = folder.ParseName(Path.GetFileName(filePath));

                string duration = null;

                // Deal with different versions of OS
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    duration = folder.GetDetailsOf(folderitem, 27);
                }
                else
                {
                    duration = folder.GetDetailsOf(folderitem, 21);
                }

                duration = string.IsNullOrEmpty(duration) ? "00:00:00" : duration;
                return(Tuple.Create(duration, GetTimeInMillisecond(duration)));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private string GetFileInfo()
        {
            string dirname;
            string filename;
            string header;
            string data;
            string info = "";

            Shell32.Shell shell = new Shell32.Shell();
            dirname  = Path.GetDirectoryName(trackPath);
            filename = Path.GetFileName(trackPath);
            Shell32.Folder     folder     = shell.NameSpace(dirname);
            Shell32.FolderItem folderitem = folder.ParseName(filename);
            info = filename + "\n";
            for (int i = 1; i <= 350; i++)
            {
                header = folder.GetDetailsOf(null, i);
                data   = folder.GetDetailsOf(folderitem, i);
                if (!(String.IsNullOrEmpty(header)) && !(String.IsNullOrEmpty(data)))
                {
                    if (header == "Wolne miejsce" || header == "Całkowity rozmiar")
                    {
                        i++;
                    }
                    else
                    {
                        info += $"{header}: {data}\r";
                    }
                }
            }
            return(info);
        }
        private Dictionary <string, string> GetExtendedProperties(string filePath)
        {
            var directory   = Path.GetDirectoryName(filePath);
            var shell       = new Shell32.Shell();
            var shellFolder = shell.NameSpace(directory);
            var fileName    = Path.GetFileName(filePath);
            var folderitem  = shellFolder.ParseName(fileName);
            var dictionary  = new Dictionary <string, string>(StringComparer.CurrentCultureIgnoreCase);
            var i           = -1;

            while (++i < 320)
            {
                var header = shellFolder.GetDetailsOf(null, i);
                if (String.IsNullOrEmpty(header))
                {
                    continue;
                }
                var value = shellFolder.GetDetailsOf(folderitem, i);
                if (!dictionary.ContainsKey(header))
                {
                    dictionary.Add(header, value);
                }
                Console.WriteLine(header + ": " + value);
            }
            Marshal.ReleaseComObject(shell);
            Marshal.ReleaseComObject(shellFolder);
            return(dictionary);
        }
        void PopulateNovelsURLs(ComboBox cb)
        {
            List <NovelDrop> items = new List <NovelDrop>();

            // Get the shortcut's folder.
            Shell32.Folder shortcut_folder = _shell.NameSpace(_exe_dir);

            string[] fileEntries = Directory.GetFiles(_exe_dir);
            foreach (string file in fileEntries)
            {
                if (System.IO.Path.GetExtension(file).Equals(".url", StringComparison.InvariantCultureIgnoreCase))
                {
                    //Get the shortcut's file.
                    Shell32.FolderItem folder_item =
                        shortcut_folder.Items().Item(System.IO.Path.GetFileName(file));
                    // Get shortcut's information.
                    Shell32.ShellLinkObject lnk = (Shell32.ShellLinkObject)folder_item.GetLink;
                    items.Add(new NovelDrop()
                    {
                        Novel = folder_item.Name, Link = lnk.Path
                    });
                }
            }
            // Assign data to combobox
            cb.ItemsSource = items;
        }
Example #8
0
        /// <summary>
        /// extract icon from link file</summary>
        public static Bitmap extractLnkIcon(string path)
        {
            #if !MONO
            try
            {
                var shl = new Shell32.Shell();
                string lnkPath = System.IO.Path.GetFullPath(path);
                var dir = shl.NameSpace(System.IO.Path.GetDirectoryName(lnkPath));
                var itm = dir.Items().Item(System.IO.Path.GetFileName(lnkPath));
                var lnk = (Shell32.ShellLinkObject)itm.GetLink;

                String strIcon;
                lnk.GetIconLocation(out strIcon);
                Icon awIcon = Icon.ExtractAssociatedIcon(strIcon);

                return awIcon.ToBitmap();
            }
            catch (Exception e)
            {
                Program.log.write("get exe icon error: " + e.Message);
            }

            return null;
            #else
            return null;
            #endif
        }
Example #9
0
        private string GetShortcutInfo(string full_name, out string name, out string path, out string descr, out string working_dir, out string args)
        {
            name        = "";
            path        = "";
            descr       = "";
            working_dir = "";
            args        = "";
            try
            {
                // Make a Shell object.
                Shell32.Shell shell = new Shell32.Shell();

                // Get the shortcut's folder and name.
                string shortcut_path = full_name.Substring(0, full_name.LastIndexOf("\\"));
                string shortcut_name = full_name.Substring(full_name.LastIndexOf("\\") + 1);
                if (!shortcut_name.EndsWith(".lnk"))
                {
                    shortcut_name += ".lnk";
                }

                // Get the shortcut's folder.
                Shell32.Folder shortcut_folder = shell.NameSpace(shortcut_path);

                // Get the shortcut's file.
                Shell32.FolderItem folder_item = shortcut_folder.Items().Item(shortcut_name);

                if (folder_item == null)
                {
                    return("Cannot find shortcut file '" + full_name + "'");
                }
                if (!folder_item.IsLink)
                {
                    return("File '" + full_name + "' isn't a shortcut.");
                }

                // Display the shortcut's information.
                Shell32.ShellLinkObject lnk =
                    (Shell32.ShellLinkObject)folder_item.GetLink;
                name  = folder_item.Name;
                descr = lnk.Description;
                if (File.Exists(lnk.Path))
                {
                    path = lnk.Path;
                }
                else
                {
                    if (File.Exists(lnk.Path.Replace("(x86)", "")))
                    {
                        path = lnk.Path.Replace("(x86)", "");
                    }
                }
                working_dir = lnk.WorkingDirectory;
                args        = lnk.Arguments;
                return("");
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Example #10
0
        private void FindFieldContent()
        {
            textBoxTitle.Text = FindTaskParts(out string[] titles, out string[][] subtasks);

            Shell32.Shell       shell  = new Shell32.Shell();
            Shell32.Folder      folder = shell.NameSpace(FIELD_PIC_PATH);
            Shell32.FolderItems items  = folder.Items();

            for (int i = 0; i < items.Count; i++)
            {
                var fileName = folder.GetDetailsOf(items.Item(i), 0);
                DecompilePicName(Path.GetFileNameWithoutExtension(fileName), out var position, out var taskNumber);

                fields[position - 1].TaskNumbers.Add(taskNumber);
                fields[position - 1].Title = titles[position - 1];

                if (subtasks[position - 1].Length < taskNumber)
                {
                    MessageBox.Show("Nem tartozik feladat a képhez:" + fileName);
                    fields[position - 1].Tasks.Add("");
                }
                else
                {
                    fields[position - 1].Tasks.Add(subtasks[position - 1][taskNumber - 1]);
                }

                fields[position - 1].Paths.Add(FIELD_PIC_PATH + fileName);
            }
        }
Example #11
0
        public void GetData(string location)
        {
            try
            {
                ShellObject song = ShellObject.FromParsingName(location);
                nameTextBox.Text    = Index.GetValue(song.Properties.GetProperty(SystemProperties.System.FileName));
                aArtistTextBox.Text = Index.GetValue(song.Properties.GetProperty(SystemProperties.System.Music.AlbumArtist));
                titleTextBox.Text   = Index.GetValue(song.Properties.GetProperty(SystemProperties.System.Title));
                albumTextBox.Text   = Index.GetValue(song.Properties.GetProperty(SystemProperties.System.Music.AlbumTitle));
                yearTextBox.Text    = Index.GetValue(song.Properties.GetProperty(SystemProperties.System.Media.Year));
                lyricsTextBox.Text  = Index.GetValue(song.Properties.GetProperty(SystemProperties.System.Music.Lyrics));

                Shell32.Shell      shell      = new Shell32.Shell();
                Shell32.Folder     objFolder  = shell.NameSpace(System.IO.Path.GetDirectoryName(location));
                Shell32.FolderItem folderItem = objFolder.ParseName(System.IO.Path.GetFileName(location));
                contributingTextBox.Text = objFolder.GetDetailsOf(folderItem, 13);
                genreBox.Text            = objFolder.GetDetailsOf(folderItem, 16);
            }
            catch (ShellException)
            {
                MessageBox.Show("File not found exception!", "Error");
                Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
                Close();
            }
        }
        internal static List <string> GetAllVideoMetadata(string filePath)
        {
            var shl     = new Shell32.Shell();
            var fldr    = shl.NameSpace(Path.GetDirectoryName(filePath));
            var itm     = fldr.ParseName(Path.GetFileName(filePath));
            var headers = new Dictionary <short, string>();
            var output  = new List <string>();

            for (short i = 0; i < short.MaxValue; i++)
            {
                var header = fldr.GetDetailsOf(null, i);
                if (string.IsNullOrEmpty(header))
                {
                    continue;
                }
                headers.Add(i, header);
            }

            foreach (var header in headers)
            {
                output.Add($"{header.Key} => {header.Value}: >{fldr.GetDetailsOf(itm, header.Key)}<");
            }

            return(output);
        }
Example #13
0
    static void Main(string[] args)
    {
        Console.Title = "Extended file properties.";
        List <string> arrHeaders = new List <string>();

        Shell32.Shell  shell = new Shell32.Shell();
        Shell32.Folder objFolder;
        objFolder = shell.NameSpace(@"C:\Users\Admin\Pictures\PBS Docs");
        for (int i = 0; i < short.MaxValue; i++)
        {
            string header = objFolder.GetDetailsOf(null, i);
            if (String.IsNullOrEmpty(header))
            {
                break;
            }
            arrHeaders.Add(header);
        }
        foreach (Shell32.FolderItem2 item in objFolder.Items())
        {
            for (int i = 0; i < arrHeaders.Count; i++)
            {
                Console.WriteLine("{0}\t{1}: {2}", i, arrHeaders[i], objFolder.GetDetailsOf(item, i));
            }
        }
    }
Example #14
0
        private string GetShortcutInfo(string full_name)
        {
            string path = "";

            try
            {
                Shell32.Shell shell         = new Shell32.Shell();
                string        shortcut_path = full_name.Substring(0, full_name.LastIndexOf("\\"));
                string        shortcut_name = full_name.Substring(full_name.LastIndexOf("\\") + 1);
                if (!shortcut_name.EndsWith(".lnk"))
                {
                    shortcut_name += ".lnk";
                }
                Shell32.Folder     shortcut_folder = shell.NameSpace(shortcut_path);
                Shell32.FolderItem folder_item     = shortcut_folder.Items().Item(shortcut_name);

                if (folder_item == null)
                {
                    if (!folder_item.IsLink)
                    {
                        return("File '" + full_name + "' isn't a shortcut.");
                    }
                }
                Shell32.ShellLinkObject lnk =
                    (Shell32.ShellLinkObject)folder_item.GetLink;
                path = lnk.Path;
                return(path);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Example #15
0
        // ファイルのプロパティからイメージの高さを取得
        private int GetFileHeightProperty(string filePath)
        {
            Shell32.Shell shell  = new Shell32.Shell();
            string        res    = "";
            int           height = 0;

            try
            {
                Shell32.Folder     objFolder  = shell.NameSpace(System.IO.Path.GetDirectoryName(filePath));
                Shell32.FolderItem folderItem = objFolder.ParseName(System.IO.Path.GetFileName(filePath));

                for (int i = 0; i < 300; i++)
                {
                    if (objFolder.GetDetailsOf("", i) == "高さ")
                    {
                        res = objFolder.GetDetailsOf(folderItem, i);
                        break;
                    }
                }

                Regex regex = new Regex("[0-9]+");
                Match match = regex.Match(res);
                if (match.Success)
                {
                    height = int.Parse(match.Value);
                }
            }
            catch
            {
                height = 0;
            }

            return(height);
        }
Example #16
0
        public void                     onStartup()
        {
            Shell32.Shell               shell = new Shell32.Shell();
            Shell32.Folder              objFolder = shell.NameSpace(@"C:\Windows");

            this.files.Clear();
            foreach (string name in ColumnListPerName)
                this.files.Columns.Add(name);
            foreach (int id in ColumnListPerID)
            {
                string header = objFolder.GetDetailsOf(null, id);
                if (String.IsNullOrEmpty(header))
                    break;
                while (this.files.Columns.Contains(header))
                    header += "_";
                header = header.Replace("'", "_").Replace("’", "_");
                Debug.WriteLine("creating column named " + header);
                this.files.Columns.Add(header);
            }

            this.files.Columns["ID"].DataType = Type.GetType("System.Int32");
            this.files.Columns[objFolder.GetDetailsOf(null, 26).Replace("'", "_").Replace("’", "_")].DataType = Type.GetType("System.Int32");
            //this.files.Columns["Longueur"].DataType = Type.GetType("System.TimeSpan");
            this.files.Columns["URI"].DataType = typeof(System.Uri);
            ProcessLibraries();
            this.files.AcceptChanges();
        }
Example #17
0
        //Read above for copy instructions
        private static void Copy(string startFile, string folderPath)
        {
            if (!File.Exists(startFile))
                throw new FileNotFoundException();

            if (!Directory.Exists(folderPath))
                Directory.CreateDirectory(folderPath);

            Shell32.Shell objShell = new Shell32.Shell();
            Shell32.Folder destinationFolder = objShell.NameSpace(folderPath);
            Shell32.Folder sourceFile = objShell.NameSpace(startFile);
            foreach (var file in sourceFile.Items())
            {
                destinationFolder.CopyHere(file, 16);
            }
        }
Example #18
0
        internal static bool IsShortcut(string path)
        {
            if (!File.Exists(path))
            {
                return(false);
            }

            string directory = Path.GetDirectoryName(path);
            string file      = Path.GetFileName(path);

            try
            {
                Shell32.Shell      shell      = new Shell32.Shell();
                Shell32.Folder     folder     = shell.NameSpace(directory);
                Shell32.FolderItem folderItem = folder.ParseName(file);

                if (folderItem != null)
                {
                    return(folderItem.IsLink);
                }
            }
            catch { }

            return(false);
        }
Example #19
0
        private static void CollectFiles(string folder)
        {
            Shell32.Shell shell = new Shell32.Shell();
            Shell32.Folder objFolder = shell.NameSpace(folder);

            foreach (Shell32.FolderItem2 item in objFolder.Items())
            {
                if (item.IsFolder)
                    CollectFiles(item.Path);
                else
                {
                    if (!item.Type.ToUpper().StartsWith("MP3") && !item.Type.ToUpper().StartsWith("MPEG"))
                    {
                        LogError(item.Name + " has unsuupported file type of " + item.Type);
                        continue;
                    }
                    FileData fileData = new FileData();
                    fileData.name = item.Name;
                    fileData.size = item.Size;
                    fileData.modified = item.ModifyDate;
                    fileData.path = item.Path;
                    fileData.type = item.Type;
                    int.TryParse(objFolder.GetDetailsOf(item, yearID), out fileData.year);
                    string properName = fileData.name.Split(new char[] { '.' })[0];
                    if (dict.ContainsKey(fileData.size))
                    {
                        LogError(fileData.name + " clashed with " + dict[fileData.size].name);
                        count++;
                    }
                    dict[fileData.size] = fileData;
                }
            }
        }
Example #20
0
        /// <summary>
        ///   Extracts the associated icon for the given file.
        /// </summary>
        /// <param name="file">
        ///   The path of the file to extract the icon from.
        /// </param>
        /// <returns>
        ///   A valid icon if the file exists and the icon was extracted succssfully, otherwise null.
        /// </returns>
        public static Icon ExtractIcon(string file)
        {
            if (string.IsNullOrWhiteSpace(file) || !File.Exists(file))
            {
                return(null);
            }

            Icon icon;

            try
            {
                Shell32.Shell shl = new Shell32.Shell();

                while (file.ToLower().EndsWith(".lnk"))
                {
                    Shell32.Folder          dir = shl.NameSpace(Path.GetDirectoryName(file));
                    Shell32.FolderItem      itm = dir.Items().Item(Path.GetFileName(file));
                    Shell32.ShellLinkObject lnk = (Shell32.ShellLinkObject)itm.GetLink;

                    file = lnk.Target.Path;
                }

                icon = Icon.ExtractAssociatedIcon(file);
            }
            catch (Exception e)
            {
                return(Logger.LogReturn <Icon>("Failed extracting icon from \"" + file + "\": " + e.Message, null, LogType.Error));
            }

            return(icon);
        }
Example #21
0
        public void                     onStartup()
        {
            Shell32.Shell  shell     = new Shell32.Shell();
            Shell32.Folder objFolder = shell.NameSpace(@"C:\Windows");

            this.files.Clear();
            foreach (string name in ColumnListPerName)
            {
                this.files.Columns.Add(name);
            }
            foreach (int id in ColumnListPerID)
            {
                string header = objFolder.GetDetailsOf(null, id);
                if (String.IsNullOrEmpty(header))
                {
                    break;
                }
                while (this.files.Columns.Contains(header))
                {
                    header += "_";
                }
                header = header.Replace("'", "_").Replace("’", "_");
                Debug.WriteLine("creating column named " + header);
                this.files.Columns.Add(header);
            }

            this.files.Columns["ID"].DataType = Type.GetType("System.Int32");
            this.files.Columns[objFolder.GetDetailsOf(null, 26).Replace("'", "_").Replace("’", "_")].DataType = Type.GetType("System.Int32");
            //this.files.Columns["Longueur"].DataType = Type.GetType("System.TimeSpan");
            this.files.Columns["URI"].DataType = typeof(System.Uri);
            ProcessLibraries();
            this.files.AcceptChanges();
        }
        /// <summary>
        /// 获取MD5和播放时长
        /// </summary>
        /// <param name="FilePathName"></param>
        /// <returns></returns>
        public ViewModelVideoItem GetItem(string FilePathName)
        {
            ViewModelVideoItem newItem = new ViewModelVideoItem();

            newItem.Name          = FilePathName.Substring(FilePathName.LastIndexOf("\\") + 1);
            newItem.ReRelativeUrl = FilePathName;
            int sum = 0;

            if (newItem.Name.Substring(newItem.Name.LastIndexOf(".")) == ".wmv" || newItem.Name.Substring(newItem.Name.LastIndexOf(".")) == ".WMV")
            {
                Shell32.Shell      shell      = new Shell32.Shell();
                Shell32.Folder     folder     = shell.NameSpace(FilePathName.Substring(0, FilePathName.LastIndexOf("\\")));
                Shell32.FolderItem folderitem = folder.ParseName(newItem.Name);
                string             len;
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    len = folder.GetDetailsOf(folderitem, 27);
                }
                else
                {
                    len = folder.GetDetailsOf(folderitem, 21);
                }

                string[] str = len.Split(new char[] { ':' });

                sum = int.Parse(str[0]) * 3600 + int.Parse(str[1]) * 60 + int.Parse(str[2]) + 1;
            }
            newItem.SunTime  = sum;
            newItem.MD5Value = SeatManage.SeatManageComm.SeatComm.GetMD5HashFromFile(newItem.ReRelativeUrl);
            return(newItem);
        }
Example #23
0
        /// <summary>
        /// 长度秒(支持mp4?)
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static int GetMediaTimeLenSecond(string path)
        {
            try
            {
                Shell32.Shell shell = new Shell32.Shell();
                //文件路径
                Shell32.Folder folder = shell.NameSpace(path.Substring(0, path.LastIndexOf("\\")));
                //文件名称
                Shell32.FolderItem folderitem = folder.ParseName(path.Substring(path.LastIndexOf("\\") + 1));
                string             len;
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    len = folder.GetDetailsOf(folderitem, 27);
                }
                else
                {
                    len = folder.GetDetailsOf(folderitem, 21);
                }

                string[] str = len.Split(new char[] { ':' });
                int      sum = 0;
                sum = int.Parse(str[0]) * 60 * 60 + int.Parse(str[1]) * 60 + int.Parse(str[2]);

                return(sum);
            }
            catch (Exception ex) { return(0); }
        }
Example #24
0
 static void Main()
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Shell32.Shell  shell   = new Shell32.Shell();
     Shell32.Folder recycle = shell.NameSpace(10);
     Application.Run(new frmMain(recycle));
 }
Example #25
0
        public static ShortcutInfo GetShortcutInfo(string full_name)
        {
            ShortcutInfo result = new ShortcutInfo();

            try
            {
                if (System.IO.File.Exists(full_name))
                {
                    // WshShellClass shell = new WshShellClass();
                    WshShell     shellx = new WshShell();                                 //Create a new WshShell Interface
                    IWshShortcut link   = (IWshShortcut)shellx.CreateShortcut(full_name); //Link the interface to our shortcut
                }

                // Make a Shell object.
                Shell32.Shell shell = new Shell32.Shell();

                // Get the shortcut's folder and name.
                string shortcut_path = full_name.Substring(0, full_name.LastIndexOf("\\"));
                string shortcut_name = full_name.Substring(full_name.LastIndexOf("\\") + 1);
                if (!shortcut_name.EndsWith(".lnk"))
                {
                    shortcut_name += ".lnk";
                }

                // Get the shortcut's folder.
                Shell32.Folder shortcut_folder = shell.NameSpace(shortcut_path);

                // Get the shortcut's file.
                Shell32.FolderItem folder_item = shortcut_folder.Items().Item(shortcut_name);

                if (folder_item == null)
                {
                    result.isError      = true;
                    result.ErrorMessage = "Cannot find shortcut file '" + full_name + "'";
                }
                if (!folder_item.IsLink)
                {
                    result.isError      = true;
                    result.ErrorMessage = "File '" + full_name + "' isn't a shortcut.";
                }

                // Display the shortcut's information.
                Shell32.ShellLinkObject lnk = (Shell32.ShellLinkObject)folder_item.GetLink;

                result.Name             = folder_item.Name;
                result.Description      = lnk.Description;
                result.Path             = lnk.Path;
                result.WorkingDirectory = lnk.WorkingDirectory;
                result.Args             = lnk.Arguments;
                return(result);
            }
            catch (Exception ex)
            {
                result.isError      = true;
                result.ErrorMessage = ex.Message;
                return(result);
            }
        }
Example #26
0
        public static string GetLnkTarget(Shell32.Shell shell, string lnkPath)
        {
            lnkPath = Path.GetFullPath(lnkPath);
            var dir = shell.NameSpace(Path.GetDirectoryName(lnkPath));
            var itm = dir.Items().Item(Path.GetFileName(lnkPath));
            var lnk = (Shell32.ShellLinkObject)itm.GetLink;

            return(lnk.Target.Path);
        }
Example #27
0
        //禁用 SetNetworkAdapter(False)
        //启用 SetNetworkAdapter(True)
        //添加引用system32\shell32.dll

/// <summary>
/// 通过网络连接名,修改网络启用,停用状态
/// </summary>
/// <param name="status">启用true,停用false</param>
/// <param name="pNetworkConnection">网络连接名</param>
/// <returns></returns>
        public static bool SetNetworkAdapterByShell(bool status, string pNetworkConnection)
        {
            const string discVerb = "停用(&B)"; // "停用(&B)";
            const string connVerb = "启用(&A)"; // "启用(&A)";
            const string network  = "网络连接";   //"网络连接";
            //const string networkConnection = this._netCardName; // "本地连接"

            string sVerb = null;

            if (status)
            {
                sVerb = connVerb;
            }
            else
            {
                sVerb = discVerb;
            }

            Shell32.Shell  sh     = new Shell32.Shell();
            Shell32.Folder folder = sh.NameSpace(Shell32.ShellSpecialFolderConstants.ssfCONTROLS);

            try
            {
                //进入控制面板的所有选项
                foreach (Shell32.FolderItem myItem in folder.Items())
                {
                    //进入网络连接
                    if (myItem.Name == network)
                    {
                        Shell32.Folder fd = (Shell32.Folder)myItem.GetFolder;
                        foreach (Shell32.FolderItem fi in fd.Items())
                        {
                            //找到本地连接
                            if ((fi.Name == pNetworkConnection))
                            {
                                //找本地连接的所有右键功能菜单
                                foreach (Shell32.FolderItemVerb Fib in fi.Verbs())
                                {
                                    if (Fib.Name == sVerb)
                                    {
                                        Fib.DoIt();
                                        return(true);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(false);
            }
            return(true);
        }
Example #28
0
        static void runRenamer(string p)
        {
            string songTitle = "bartFart";
            //File songFile = Directory.get
            string songArtist = "ShortLife";

            string path       = p;
            string targetPath = @"C:\NewSongs\";

            //get the file(s)
            string[] songfiles = Directory.GetFiles(path);

            foreach (string song in songfiles)
            {
                List <string> arrHeaders = new List <string>();

                Shell32.Shell      shell      = new Shell32.Shell();
                Shell32.Folder     objFolder  = shell.NameSpace(System.IO.Path.GetDirectoryName(song));
                Shell32.FolderItem folderItem = objFolder.ParseName(System.IO.Path.GetFileName(song));

                for (int i = 0; i < short.MaxValue; i++)
                {
                    string header = objFolder.GetDetailsOf(null, i);
                    if (String.IsNullOrEmpty(header))
                    {
                        break;
                    }
                    arrHeaders.Add(header);
                }

                for (int i = 0; i < arrHeaders.Count; i++)
                {
                    Console.WriteLine("{0}\t{1}: {2}", i, arrHeaders[i], objFolder.GetDetailsOf(folderItem, i));
                }
                songTitle  = objFolder.GetDetailsOf(folderItem, 21);
                songArtist = objFolder.GetDetailsOf(folderItem, 13);
                FileAttributes attributes = File.GetAttributes(song);

                FileInfo fi = new FileInfo("bart.txt");
                //fi.a

                ////get the file property

                ////check if the dir exists
                if (!System.IO.Directory.Exists(targetPath + songArtist))
                {
                    Directory.CreateDirectory(targetPath + songArtist);
                }
                ////copy the file to target dir


                System.IO.File.Move(song, targetPath + songArtist + @"\" + songTitle + ".m4a");
                //rename the file to the Title of the Song
            }
            Console.ReadLine();
        }
Example #29
0
        /// <summary>
        /// Returns the destination of a shortcut file
        /// </summary>
        /// <param name="path">Path of shortcut</param>
        /// <returns>Path of destination for shortcut</returns>
        protected static string GetDestination(string path)
        {
            var shl     = new Shell32.Shell();
            var lnkPath = System.IO.Path.GetFullPath(path);
            var dir     = shl.NameSpace(System.IO.Path.GetDirectoryName(lnkPath));
            var itm     = dir.Items().Item(System.IO.Path.GetFileName(lnkPath));
            var lnk     = (Shell32.ShellLinkObject)itm.GetLink;

            return(lnk.Target.Path);
        }
Example #30
0
        public static String handleExtName(String file)
        {
            string fileName = Path.GetFileName(file);

            file = Path.GetDirectoryName(Path.GetFullPath(file));
            Shell32.Folder     shellFolder = shell.NameSpace(file);
            Shell32.FolderItem shellItem   = shellFolder.Items().Item(fileName);

            return(shellItem.Name);
        }
Example #31
0
 private int video_handle(string path)
 {
     try
     {
         log("{0} 视频信息读取 ing..", path);
         Shell32.Shell shell = new Shell32.Shell();
         //文件路径
         Shell32.Folder folder = shell.NameSpace(path.Substring(0, path.LastIndexOf("\\")));
         //文件名称
         Shell32.FolderItem folderitem = folder.ParseName(path.Substring(path.LastIndexOf("\\") + 1));
         string             len;
         //string kbps = folder.GetDetailsOf(folderitem, 308);
         //int i = 0;
         //while (true)
         //{
         //    //获取属性名称
         //    string key = folder.GetDetailsOf(null, i);
         //    if (string.IsNullOrEmpty(key))
         //    {
         //        //当无属性可取时,退出循环
         //        break;
         //    }
         //    //获取属性值
         //    string value = folder.GetDetailsOf(folderitem, i);
         //    Console.WriteLine("{0}:{1}", key, value);
         //    i++;
         //}
         //多系统兼容
         if (Environment.OSVersion.Version.Major >= 6)
         {
             len = folder.GetDetailsOf(folderitem, 27);
         }
         else
         {
             len = folder.GetDetailsOf(folderitem, 21);
         }
         string[] str = len.Split(new char[] { ':' });
         int      sum = 0;
         if (str.Length == 3)
         {
             sum = int.Parse(str[0]) * 60 * 60 + int.Parse(str[1]) * 60 + int.Parse(str[2]);
             log("视频信息{0}s", sum);
         }
         else
         {
             error("视频信息读取失败,也行是系统功能被限制!");
         }
         return(sum);
     }
     catch (Exception ex)
     {
         error("读取视频信息发生错误{0}", ex.Message);
         return(0);
     }
 }
Example #32
0
 public void ZipFolder(string sourceFolder, string dstFile)
 {
     byte[] emptyzip = new byte[] { 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
     try
     {
         FileStream fs = File.Create(dstFile);
         fs.Write(emptyzip, 0, emptyzip.Length);
         fs.Flush();
         fs.Close();
         fs = null;
         Shell32.Shell       sc        = new Shell32.Shell();
         Shell32.Folder      SrcFlder  = sc.NameSpace(sourceFolder);
         Shell32.Folder      DestFlder = sc.NameSpace(dstFile);
         Shell32.FolderItems items     = SrcFlder.Items();
         DestFlder.CopyHere(items, 20);
     }
     catch
     {
     }
 }
        private LinkFile CreateLinkItem(FileSystemInfo item, FileInfo fi)
        {
            string directory = Path.GetDirectoryName(item.FullName);
            string file      = Path.GetFileName(item.FullName);

            Shell32.Shell           shell      = new Shell32.Shell();
            Shell32.Folder          folder     = shell.NameSpace(directory);
            Shell32.FolderItem      folderItem = folder.ParseName(file);
            Shell32.ShellLinkObject link       = (Shell32.ShellLinkObject)folderItem.GetLink;
            return(ItemFactory.CreateLink(item.FullName, item.Name, fi.Length.ToString(), GetOwner(fi), (FileType)item.Attributes, item.CreationTime, !fi.IsReadOnly, item.LastAccessTime, item.LastWriteTime, item.Extension, link.Path, new string[] { link.Arguments }, link.Description));
        }
Example #34
0
        /// <summary>
        /// Reads .lnk file and returns target property.
        /// </summary>
        /// <param name="lnkPath"></param>
        /// <returns></returns>
        public static string GetLnkTarget(string lnkPath)
        {
            var shl = new Shell32.Shell();                     // Move this to class scope

            lnkPath = System.IO.Path.GetFullPath(lnkPath);
            var dir = shl.NameSpace(System.IO.Path.GetDirectoryName(lnkPath));
            var itm = dir.Items().Item(System.IO.Path.GetFileName(lnkPath));
            var lnk = (Shell32.ShellLinkObject)itm.GetLink;

            return(lnk.Path);
        }
Example #35
0
        public string ReadLink(string path)
        {
            string directory = Path.GetDirectoryName(path);
            string file      = Path.GetFileName(path);

            Shell32.Shell           shell      = new Shell32.Shell();
            Shell32.Folder          folder     = shell.NameSpace(directory);
            Shell32.FolderItem      folderItem = folder.ParseName(file);
            Shell32.ShellLinkObject link       = (Shell32.ShellLinkObject)folderItem.GetLink;
            return(link.Path);
        }
Example #36
0
        public static void ZipFile(string Input, string Filename)
        {
            Shell32.Shell Shell = new Shell32.Shell();

            //Create our Zip File
            CreateZipFile(Filename);

            //Copy the file or folder to it
            Shell.NameSpace(Filename).CopyHere(Input, 0);

            //If you can write the code to wait for the code to finish, please let me know
            System.Threading.Thread.Sleep(1000);
        }
Example #37
0
        public Main()
        {
            InitializeComponent();
            //
            // TODO: Add any constructor code after InitializeComponent call
            //
            SplitView.SplitPosition = this.Width / 2;

            m_Shell = new Shell32.ShellClass();
            m_RootShell = m_Shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfDRIVES);

            InitializeIconFolder();
            FillLocalView(m_RootShell);
        }
Example #38
0
        public static bool CopyFontToWindowsFontFolder(string fontFilePath)
        {
            FileInfo fontFile = new FileInfo(fontFilePath);
            if (!fontFile.Exists)
                return false;

            var windowsFontFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
            var shell = new Shell32.Shell();
            var destinationPath = Path.Combine(windowsFontFolderPath, Path.GetFileName(fontFilePath));
            var folder = shell.NameSpace(windowsFontFolderPath);
            folder.CopyHere(fontFilePath, 32);

            return true;
        }
 public static string GetLnkTarget(string lnkPath)
 {
     try
     {
         var shl = new Shell32.Shell();         // Move this to class scope
         var dir = shl.NameSpace(System.IO.Path.GetDirectoryName(lnkPath));
         var itm = dir.Items().Item(System.IO.Path.GetFileName(lnkPath));
         var lnk = (Shell32.ShellLinkObject)itm.GetLink;
         return lnk.Target.Path;
     }
     catch (Exception)
     {
         return lnkPath;
     }
 }
Example #40
0
        public SharpFTP()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
            SplitView.SplitPosition = this.Width / 2;

            m_Shell = new Shell32.ShellClass();
            m_RootShell = m_Shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfDRIVES);

            InitializeIconFolder();
            FillLocalView (m_RootShell);
        }
        public static string GetLnkTarget(string lnkPath)
        {
            FileInfo fileInfo = new FileInfo(lnkPath);
            if (fileInfo.Extension.ToUpper() == ".LNK")
            {
                var shl = new Shell32.Shell();         // Move this to class scope
                lnkPath = System.IO.Path.GetFullPath(lnkPath);
                var dir = shl.NameSpace(System.IO.Path.GetDirectoryName(lnkPath));
                var itm = dir.Items().Item(System.IO.Path.GetFileName(lnkPath));

                var lnk = (Shell32.ShellLinkObject)itm.GetLink;
                return lnk.Target.Path;
            }
            else
            {
                return string.Empty;
            }
        }
        public static List<Song> ReadTags(string[] filepaths)
        {
            //Song mp3File = new Song();

            //parse file name

            List<Song> songs = new List<Song>();
            string webpath;

            foreach (string filepath in filepaths)
            {

                string fileName = filepath.Substring(filepath.LastIndexOf(@"\") + 1);

                //parse file path
                string filePath = filepath.Substring(0, filepath.LastIndexOf(@"\") + 1);

                //filepath.

                //create shell instance
                Shell32.Shell shell = new Shell32.Shell();
                //set the namespace to file path
                Shell32.Folder folder = shell.NameSpace(filePath);
                //get ahandle to the file
                Shell32.FolderItem folderItem = folder.ParseName(fileName);
                //did we get a handle ?
                if (folderItem != null)
                {
                    webpath = filepath.Substring(filepath.LastIndexOf("StreamTunes") + 11);
                    //folder.
                    songs.Add(new Song(webpath, artist: folder.GetDetailsOf(folderItem,13), album: folder.GetDetailsOf(folderItem, 14),
                        name: folder.GetDetailsOf(folderItem, 21)));

                }
                //clean ip
                folderItem = null;
                folder = null;
                shell = null;
                //return mp3File instance

            }

            return songs;
        }
Example #43
0
        // If you are using Visual Studio, you can simply add a reference to
        // the COM library "Microsoft Shell Control And Automation"
        // or to SHELL32.DLL directly, and then use the following code:
        public static Shell32.ShellLinkObject GetShellLinkObject(string shortcutPath)
        {
            string extOnly = System.IO.Path.GetExtension(shortcutPath);
            if (extOnly != ".lnk")
                return null; // not shortcut

            string pathOnly = System.IO.Path.GetDirectoryName(shortcutPath);
            string filenameOnly = System.IO.Path.GetFileName(shortcutPath);

            Shell32.Shell shell = new Shell32.Shell();
            Shell32.Folder folder = shell.NameSpace(pathOnly);
            Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
            if (folderItem != null)
            {
                return (Shell32.ShellLinkObject)folderItem.GetLink;
            }

            return null; // not found
        }
Example #44
0
        public static string GetLnkTarget(string shortcutFullPath)
        {
            try
            {
                Shell32.Shell shell = new Shell32.Shell();
                Shell32.Folder folder = shell.NameSpace(Path.GetDirectoryName(shortcutFullPath));
                Shell32.FolderItem folderItem = folder.Items().Item(Path.GetFileName(shortcutFullPath));
                Shell32.ShellLinkObject currentLink = (Shell32.ShellLinkObject)folderItem.GetLink;
                return currentLink.Path;

            }

            catch (NullReferenceException nrEx)
            {
                Console.WriteLine (nrEx.Message);
                return ("NullReferenceException");
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.Message);
                return ("Exception");
            }
        }
Example #45
0
        public static void SetLnkTarget(string shortcutFullPath, string newTarget)
        {
            try
            {
                // Load the shortcut.
                Shell32.Shell shell = new Shell32.Shell();

                Shell32.Folder folder = (Shell32.Folder)shell.NameSpace(Path.GetDirectoryName(shortcutFullPath));
                Shell32.FolderItem folderItem = folder.Items().Item(Path.GetFileName(shortcutFullPath));
                Shell32.ShellLinkObject currentLink = (Shell32.ShellLinkObject)folderItem.GetLink;

                //Assign the new path here. This value is not read-only.
                currentLink.Path = newTarget;

                // Save the link to commit the changes.
                currentLink.Save();

            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.Message);
            }
        }
Example #46
0
        public static bool IsLink(string shortcutFilename)
        {
            try
              {
            string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
            string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);

            Shell32.Shell shell = new Shell32.Shell();
            Shell32.Folder folder = shell.NameSpace(pathOnly);
            Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
            if (folderItem != null)
            {
              return folderItem.IsLink;
            }
            return false; // not found
              }
              catch (Exception)
              {
            return false;
              }
        }
Example #47
0
        public void ZipFolder(string sourceFolder, string dstFile)
        {
            byte[] emptyzip = new byte[] { 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            try
            {
                FileStream fs = File.Create(dstFile);
                fs.Write(emptyzip, 0, emptyzip.Length);
                fs.Flush();
                fs.Close();
                fs = null;
                Shell32.Shell sc = new Shell32.Shell();
                Shell32.Folder SrcFlder = sc.NameSpace(sourceFolder);
                Shell32.Folder DestFlder = sc.NameSpace(dstFile);
                Shell32.FolderItems items = SrcFlder.Items();
                DestFlder.CopyHere(items, 20);
            }
            catch
            {

            }
        }
Example #48
0
        /// <summary>
        /// Gets the file information stored in the Extended File Details.
        /// </summary>
        /// <param name="file"></param>
        /// <param name="fUseCachedFolders"></param>
        /// <returns></returns>
        private string GetExtendedFileDetails(FileInfo file, bool fUseCachedFolders = true)
        {
            bool fDebugOutput = true;
            bool fDebugOutputTraceLevel = false;
            bool fDebugTrace = fDebugOutput && fDebugOutputTraceLevel;

            Logging.LogLineIf(fDebugTrace, "GetExtendedFileDetails(): entered.");

            string retVal = "";

            // Note that you can still force the read-from-disk way by calling GetExtendedFileDetails(FileFullname, false).

            // create our Shell32 object
            Shell32.Folder objFolder;

            // Cached method: get the objFolder from a Dictionary of
            // Shell32.Folders we built during startup, instead of creating a new
            // shell object every time.
            if (fUseCachedFolders)
            {
                if (!MainFiles.ShellDict.TryGetValue(file.DirectoryName, out objFolder))
                {
                    Logging.LogLineIf(fDebugOutput, "  GetExtendedFileDetails(): Failed to get objFolder from Dictionary. Falling back to read from disk method.");
                    GetExtendedFileDetails(file, false);
                }
            }
            else        // for some reason, desired objfolder was not found in cache, so build it
            {
                Shell32.Shell shell = new Shell32.Shell();
                // objFolder = shell.NameSpace(Path.GetDirectoryName(file.FullName));
                objFolder = shell.NameSpace(file.DirectoryName);
            }

            // get the data block for the file
            Shell32.FolderItem2 xItem = (Shell32.FolderItem2)objFolder.ParseName(file.Name);

            // get the Comments at index 24 from the data
            bool fGot24 = false;
            string stReturn = objFolder.GetDetailsOf(xItem, 24).ToString().Trim();
            if (!string.IsNullOrEmpty(stReturn) && !string.IsNullOrWhiteSpace(stReturn))
            {
                retVal += stReturn;
                fGot24 = true;
            }

            // Get the Tags at index 18
            stReturn = objFolder.GetDetailsOf(xItem, 18).ToString().Trim();
            if (!string.IsNullOrEmpty(stReturn) && !string.IsNullOrWhiteSpace(stReturn))
            {
                // Let's give ourselves a new line for every tag
                stReturn = stReturn.Replace(";", Environment.NewLine + "  ");
                if (fGot24) retVal += Environment.NewLine;
                retVal += "Tags: " + Environment.NewLine + "   " + stReturn;
            }

            Logging.LogLineIf(fDebugTrace, "GetExtendedFileDetails(): exiting.");
            return retVal;
        }
Example #49
0
        static void Main(string[] args)
        {
            LoadConfigurations();
            Shell32.Shell shell = new Shell32.Shell();
            Shell32.Folder objFolder;

            objFolder = shell.NameSpace(inputFolder);

            for (int i = 0; i < short.MaxValue; i++)
            {
                string header = objFolder.GetDetailsOf(null, i);
                if (String.IsNullOrEmpty(header))
                    break;
                if (header.Equals("Year"))
                {
                    yearID = i;
                    break;
                }
            }
            CollectFiles(inputFolder);
            if (Directory.Exists(outputFolder))
                DeleteDirectory(outputFolder);
            Directory.CreateDirectory(outputFolder);
            OrganisedCopy(outputFolder);
        }
Example #50
0
 /// <summary>
 /// 本地浏览器右键菜单“属性”条目事件
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void LocalPopupMenuProperty_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
 {
     const string discVerb = "属性(&R)";
     Point p = this.ListViewLocal.PointToClient(new Point(menutrippoint.X, menutrippoint.Y));
     string sourceFile = LocalPath + ListViewLocal.GetItemAt(p.X, p.Y).Text;
     FileInfo file = new FileInfo(sourceFile);
     Shell32.Shell shell = new Shell32.Shell();
     Shell32.Folder folder = shell.NameSpace(file.DirectoryName);
     Shell32.FolderItem folderItem = folder.ParseName(file.Name);
     foreach (Shell32.FolderItemVerb Fib in folderItem.Verbs())
     {
         if (Fib.Name == discVerb)
         {
             Fib.DoIt();
             break;
         }
     }
 }
Example #51
0
        static void Main(string[] args)
        {
            bool modded = false;

            Console.WriteLine("Traugdor's Minecraft Modding Program");
            Console.WriteLine();
            Console.Write("Doing important stuff");
            string folderlocation = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString();
            folderlocation += @"\.minecraft";
            Console.Write(".");
            string modlocation = folderlocation + @"\mods";
            Console.Write(".");
            string coremodlocation = folderlocation + @"\coremods";
            Console.Write(".done");
            Console.WriteLine();
            Console.WriteLine("Minecraft folder set to:");
            Console.WriteLine(folderlocation);
            Console.WriteLine("Mods folder set to:");
            Console.WriteLine(modlocation);
            Console.WriteLine("Coremods folder set to:");
            Console.WriteLine(coremodlocation);
            Console.WriteLine();
            Console.WriteLine("Downloading files");

            WebClient downloader = new WebClient();
            if (File.Exists(folderlocation + @"\489.forgeversion"))
            {
                modded = true;
            }
            else
            {
                Console.WriteLine("Client is likely not modded.");
                Console.Write("Downloading modded client...");
                if (File.Exists(@"C:\temp\moddedcraft.zip"))
                {
                    Console.WriteLine("Client already downloaded! This is strange.");
                }
                else
                {
                    downloader.DownloadFile("http://dl.dropbox.com/u/60448852/forjamie.zip", @"C:\temp\moddedcraft.zip");
                    Console.Write("done");
                    Console.WriteLine();
                }

                Console.Write("Extracting modded client...");
                Shell32.Shell sc = new Shell32.Shell();
                Directory.CreateDirectory(@"C:\temp\moddedcraft");
                Shell32.Folder output = sc.NameSpace(@"C:\temp\moddedcraft");
                Shell32.Folder input = sc.NameSpace(@"C:\temp\moddedcraft.zip");
                output.CopyHere(input.Items(), 256);
                Console.Write("done");
                Console.WriteLine();

                Console.WriteLine("Cleaning up some things...");
                File.Delete(@"C:\temp\moddedcraft.zip");

                Console.Write("Installing modded client...");
                string clientsource = @"C:\temp\moddedcraft";
                new Microsoft.VisualBasic.Devices.Computer().FileSystem.CopyDirectory(clientsource, folderlocation, true);
                Console.Write("done");
                Console.WriteLine();

                Console.WriteLine("Cleaning up some more...");
                Directory.Delete(clientsource, true);

            }

            if (modded)
            {
                Console.WriteLine("Client already modded. Skipping modded client.");
            }
            
            //download and move mods.
            Console.WriteLine();
            Console.WriteLine("Downloading mods:");
            Console.Write("Redpower2 Core: ");
            if(File.Exists(modlocation + @"\RedPowerCore-2.0pr6.zip"))
            {
                Console.Write("Already installed! :)");
            }
            else
            {
                downloader.DownloadFile("http://dl.dropbox.com/u/60448852/RedPowerCore-2.0pr6.zip", modlocation + @"\RedPowerCore-2.0pr6.zip");
                Console.Write("Done");
            }
            Console.WriteLine();
            Console.Write("Redpower2 Digital Package: ");
            if (File.Exists(modlocation + @"\RedPowerDigital-2.0pr6.zip"))
            {
                Console.Write("Already installed! :)");
            }
            else
            {
                downloader.DownloadFile("http://dl.dropbox.com/u/60448852/RedPowerDigital-2.0pr6.zip", modlocation + @"\RedPowerDigital-2.0pr6.zip");
                Console.Write("Done");
            }
            Console.WriteLine();
            Console.Write("Redpower2 Mechanical Package: ");
            if (File.Exists(modlocation + @"\RedPowerMechanical-2.0pr6.zip"))
            {
                Console.Write("Already installed! :)");
            }
            else
            {
                downloader.DownloadFile("http://dl.dropbox.com/u/60448852/RedPowerMechanical-2.0pr6.zip", modlocation + @"\RedPowerMechanical-2.0pr6.zip");
                Console.Write("Done");
            }
            Console.WriteLine();
            Console.Write("Redpower2 Compatibility Extension: ");
            if (File.Exists(modlocation + @"\RedPowerCompat-2.0pr6.zip"))
            {
                Console.Write("Already installed! :)");
            }
            else
            {
                downloader.DownloadFile("http://dl.dropbox.com/u/60448852/RedPowerCompat-2.0pr6.zip", modlocation + @"\RedPowerCompat-2.0pr6.zip");
                Console.Write("Done");
            }
            Console.WriteLine();
            Console.Write("Balkon's Weapons Mod: ");
            if (File.Exists(modlocation + @"\Weaponmod.zip"))
            {
                Console.Write("Already installed! :)");
            }
            else
            {
                downloader.DownloadFile("http://dl.dropbox.com/u/60448852/Weaponmod.zip", modlocation + @"\Weaponmod.zip");
                Console.Write("Done");
            }
            Console.WriteLine();
            Console.Write("ChickenBones Core for NEI: ");
            if (File.Exists(coremodlocation + @"\CodeChickenCore-0.7.1.0.jar"))
            {
                Console.Write("Already installed! :)");
            }
            else
            {
                downloader.DownloadFile("http://dl.dropbox.com/u/60448852/CodeChickenCore-0.7.1.0.jar", coremodlocation + @"\CodeChickenCore-0.7.1.0.jar");
                Console.Write("Done");
            }
            Console.WriteLine();
            Console.Write("NEI Core: ");
            if (File.Exists(coremodlocation + @"\NotEnoughItems-1.4.5.1.jar"))
            {
                Console.Write("Already installed! :)");
            }
            else
            {
                downloader.DownloadFile("http://dl.dropbox.com/u/60448852/NotEnoughItems-1.4.5.1.jar", coremodlocation + @"\NotEnoughItems-1.4.5.1.jar");
                Console.Write("Done");
            }
            Console.WriteLine();
            Console.Write("NEI - Redpower interface: ");
            if (File.Exists(modlocation + @"\NEI_RedPowerPlugin-1.4.3.jar"))
            {
                Console.Write("Already installed! :)");
            }
            else
            {
                downloader.DownloadFile("http://dl.dropbox.com/u/60448852/NEI_RedPowerPlugin-1.4.3.jar", modlocation + @"\NEI_RedPowerPlugin-1.4.3.jar");
                Console.Write("Done");
            }
            Console.WriteLine();
            Console.Write("Lanterns mod: ");
            if (File.Exists(modlocation + @"\Lanterns_1.1.5_Universal.zip"))
            {
                Console.Write("Already installed! :)");
            }
            else
            {
                downloader.DownloadFile("http://dl.dropbox.com/u/60448852/Lanterns_1.1.5_Universal.zip", modlocation + @"\Lanterns_1.1.5_Universal.zip");
                Console.Write("Done");
            }
            Console.WriteLine();
            //Console.Write("Railcraft mod: ");
            //if (File.Exists(modlocation + @"\Railcraft_1.4.6-6.14.0.0.zip"))
            //{
            //    Console.Write("Already installed! :)");
            //}
            //else
            //{
            //    downloader.DownloadFile("http://dl.dropbox.com/u/60448852/Railcraft_1.4.6-6.14.0.0.zip", modlocation + @"\Railcraft_1.4.6-6.14.0.0.zip");
            //    Console.Write("Done");
            //}
            //Console.WriteLine();
            //Console.Write("NEI - Railcraft interface: ");
            //if (File.Exists(modlocation + @"\NEIPlugins-1.0.4.1.jar"))
            //{
            //    Console.Write("Already installed! :)");
            //}
            //else
            //{
            //    downloader.DownloadFile("http://dl.dropbox.com/u/60448852/NEIPlugins-1.0.4.1.jar", modlocation + @"\NEIPlugins-1.0.4.1.jar");
            //    Console.Write("Done");
            //}
            //Console.WriteLine();


            Console.WriteLine();
            Console.WriteLine("Program is finished. Enjoy your mods!");

            Console.WriteLine();
            Console.WriteLine("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
 /// <summary>
 /// Quelle: http://stackoverflow.com/questions/9454836/vb-net-c-sharp-code-to-access-target-path-of-link-lnk-files-produces-some-wr
 /// </summary>
 /// <returns></returns>
 public static string GetTargetPath(string lnkPath)
 {
     dynamic shl = new Shell32.Shell();
     // Move this to class scope
     lnkPath = System.IO.Path.GetFullPath(lnkPath);
     dynamic dir = shl.NameSpace(System.IO.Path.GetDirectoryName(lnkPath));
     dynamic itm = dir.Items().Item(System.IO.Path.GetFileName(lnkPath));
     dynamic lnk = (Shell32.ShellLinkObject)itm.GetLink;
     return lnk.Target.Path;
 }
Example #53
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (rememberMeBox.Checked == true)
            {
                StreamWriter logininfo = new StreamWriter(@"C:\GMODit\.minecraft\gmoditlastlogin");
                logininfo.WriteLine(this.username.Text);
                string encpass = "";
                string temppass = this.password.Text;
                Random randgen = new Random(234);
                
                foreach (char a in temppass.ToString())
                {
                    encpass += (char)((int)a + (randgen.Next() % 5));
                }
                logininfo.WriteLine(encpass);

                logininfo.Close();
            }
            else
            {
                StreamWriter logininfo = new StreamWriter(@"C:\GMODit\.minecraft\gmoditlastlogin"); // creates blank file; overwrites old file
                logininfo.Close();
            }

            bool ismodded = false;
            bool clientExists = false;
            string folderlocation = @"C:\GMODIT\.minecraft";
            string modlocation = folderlocation + @"\mods";
            string coremodlocation = folderlocation + @"\coremods";
            string templocation = "c:\\temp\\";

            if (Directory.Exists(folderlocation))
            {
                clientExists = true;
            }

            if (!Directory.Exists(templocation))
            {
                Directory.CreateDirectory(templocation);
            }

            if (File.Exists(folderlocation + "\\version3.modit"))
            {
                ismodded = true;
            }
            else
            {
                //download and extract the three files

                if (InternetCheck.Checked == true)
                {
                    WebClient downloader = new WebClient();
                    label4.Text = "Downloading client";
                    this.Update();
                    downloader.DownloadFile("https://site.com/link/to/client.zip", templocation + "client.zip");
                    label4.Text = "Downloading Mods";
                    this.Update();
                    downloader.DownloadFile("https://site.com/link/to/mods.zip", templocation + "mods.zip");
                    label4.Text = "Downloading Coremods";
                    this.Update();
                    downloader.DownloadFile("https://site.com/link/to/coremods.zip", templocation + "coremods.zip");

                    label4.Text = "Extracting...";
                    Shell32.Shell sc = new Shell32.Shell();
                    Directory.CreateDirectory(@"C:\temp\.minecraft");
                    Shell32.Folder output = sc.NameSpace(@"C:\temp\.minecraft\");
                    Shell32.Folder input = sc.NameSpace(templocation + "client.zip");
                    output.CopyHere(input.Items(), 256);

                    Directory.CreateDirectory(@"C:\temp\.minecraft\mods");
                    output = sc.NameSpace(@"C:\temp\.minecraft\mods");
                    input = sc.NameSpace(templocation + "mods.zip");
                    output.CopyHere(input.Items(), 256);

                    Directory.CreateDirectory(@"C:\temp\.minecraft\coremods");
                    output = sc.NameSpace(@"C:\temp\.minecraft\coremods");
                    input = sc.NameSpace(templocation + "coremods.zip");
                    output.CopyHere(input.Items(), 256);

                    label4.Text = "Cleaning up...";
                    this.Update();
                    File.Delete(templocation + "client.zip");
                    File.Delete(templocation + "mods.zip");
                    File.Delete(templocation + "coremods.zip");
                }
                else
                {
                    WebClient downloader = new WebClient();
                    label4.Text = "Downloading full client. May take a while";
                    this.Update();
                    downloader.DownloadFile("https://site.com/link/to/client_full.zip", templocation + "client_full.zip");

                    label4.Text = "Extracting...";
                    Shell32.Shell sc = new Shell32.Shell();
                    Directory.CreateDirectory(@"C:\temp\.minecraft");
                    Shell32.Folder output = sc.NameSpace(@"C:\temp\.minecraft\");
                    Shell32.Folder input = sc.NameSpace(templocation + "client_full.zip");
                    output.CopyHere(input.Items(), 256);

                    label4.Text = "Cleaning up...";
                    File.Delete(templocation + "client_full.zip");
                }

                new Microsoft.VisualBasic.Devices.Computer().FileSystem.CopyDirectory("C:\\temp\\.minecraft", folderlocation, true);

                Directory.Delete("C:\\temp\\.minecraft", true);

                clientExists = true;
                ismodded = true;
            }

            if (clientExists && ismodded)
            {
                bool authed = false;
                string user, session = "";
                string[] res = verifyUser(username.Text, password.Text, out authed);
                if (authed)
                {
                    user = res[2];
                    session = res[3];
                    StartMinecraft(user, session);
                    Application.Exit();
                }
            }
        }
Example #54
0
        private static string GetShortcutTargetFile(string shortcutFilename)
        {
            string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
            string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);

            Shell32.Shell shell = new Shell32.Shell();
            Shell32.Folder folder = shell.NameSpace(pathOnly);
            Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
            if (folderItem != null)
            {
                Shell32.ShellLinkObject link =
                (Shell32.ShellLinkObject)folderItem.GetLink;
                return link.Path;
            }
            return ""; // not found
        }
Example #55
0
        private static List<FileAndFolder> GetFilesToProcess(List<FileInformation> databaseFiles, List<string> arrHeaders, DirectoryInfo di)
        {
            var filesToProcess = new List<FileInfo>();

            if (di.Exists) {

                foreach (var fi in di.GetFiles()) {
                    var fileInfo = databaseFiles.FirstOrDefault(info => info.FileName.Equals(fi.Name, StringComparison.OrdinalIgnoreCase));

                    if (fileInfo == null) {
                        filesToProcess.Add(fi);
                    }
                    else if (fi.Length != fileInfo.Length
                                        || fi.CreationTimeUtc.NoMilliseconds() != fileInfo.CreatedDate
                                        || fi.LastWriteTimeUtc.NoMilliseconds() != fileInfo.LastWriteDate) {
                        filesToProcess.Add(fi);
                    }
                }
            }

            var retVal = new List<FileAndFolder>();

            if (filesToProcess.Count > 0) {

                var headerName = "Name";
                var nameIndex = arrHeaders.IndexOf(headerName);

                //reduce the folderinfo2 into a list we can process.

                Shell32.Shell shell = new Shell32.Shell();
                Shell32.Folder folder = shell.NameSpace(di.FullName);

                //thanks to this post http://geraldgibson.net/dnn/Home/CZipFileCompression/tabid/148/Default.aspx
                var nonfiltered = (Shell32.FolderItems3)folder.Items();
                int SHCONTF_INCLUDEHIDDEN = 128;
                int SHCONTF_NONFOLDERS = 64;
                nonfiltered.Filter(SHCONTF_INCLUDEHIDDEN | SHCONTF_NONFOLDERS, "*");

                foreach (Shell32.FolderItem2 item in nonfiltered) {
                    var value = folder.GetDetailsOf(item, nameIndex);
                    //see if we should process this item.
                    var processItem = filesToProcess.FirstOrDefault(fa => fa.Name.Equals(value, StringComparison.OrdinalIgnoreCase));
                    if (processItem != null) {
                        retVal.Add(new FileAndFolder() {
                            FileInfo = processItem,
                            FolderItem = item
                        });
                    }
                }
            }
            return retVal;
        }
Example #56
0
        private static void ProcessFolder(SQLiteConnection db, DriveInformation drive, List<string> arrHeaders, DirectoryInfo directory)
        {
            try {

                if (!directory.Exists)
                    return;

                if (IgnoreFolder(directory)) {
                    return;
                }

                //go get the cached items for the folder.

                var directoryId = DatabaseLookups.GetDirectoryId(db, drive, directory);

                var cmd = db.CreateCommand("Select * from " + typeof(FileInformation).Name + " Where DriveId = ? AND DirectoryId = ?", drive.DriveId, directoryId);
                var databaseFiles = cmd.ExecuteQuery<FileInformation>();

                //obtain the file metadata for all of the files in the directory so we can determine if we care about this folder.

                var processList = GetFilesToProcess(databaseFiles, arrHeaders, directory);

                if (processList.Count > 0) {

                    db.BeginTransaction();

                    Shell32.Shell shell = new Shell32.Shell();
                    Shell32.Folder folder = shell.NameSpace(directory.FullName);

                    foreach (var item in processList) {
                        try {
                            var fi = item.FileInfo;
                            var headerList = new List<FileAttributeInformation>();

                            for (int i = 0; i < arrHeaders.Count; i++) {

                                var header = arrHeaders[i];

                                if (!IgnoreHeader(header)) {
                                    var value = folder.GetDetailsOf(item.FolderItem, i);

                                    if (!string.IsNullOrWhiteSpace(value)) {
                                        headerList.Add(new FileAttributeInformation() {
                                            AttributeId = DatabaseLookups.GetAttributeId(db, header),
                                            Value = value
                                        });
                                    }
                                }
                            }

                            //this should have been already checked but we want to be safe.
                            if (fi.Exists) {

                                var fileInfo = databaseFiles.FirstOrDefault(info => info.FileName.Equals(fi.Name, StringComparison.OrdinalIgnoreCase));

                                if (fileInfo == null) {
                                    fileInfo = new FileInformation() {
                                        DriveId = drive.DriveId,
                                        DirectoryId = directoryId,
                                        FileName = fi.Name
                                    };
                                    SetFileInformation(fi, fileInfo);
                                    db.Insert(fileInfo);
                                    Console.WriteLine("Inserted:" + fi.FullName);
                                }
                                else {
                                    SetFileInformation(fi, fileInfo);
                                    db.Update(fileInfo);

                                    var deleteCount = db.Execute("Delete from " + typeof(FileAttributeInformation).Name + " WHERE FileId = ?", fileInfo.FileId);
                                    Console.WriteLine("Changed:" + fi.FullName);
                                }

                                //save the headers
                                headerList.ForEach(hl => hl.FileId = fileInfo.FileId);
                                db.InsertAll(headerList);
                            }
                        }
                        catch (Exception ex) {
                            Console.WriteLine(ex.ToString());
                        }
                    }

                    db.Commit();

                }

                //see if we have any additional folders. If we get access denied it will throw an error
                try {
                    foreach (var subDirectory in directory.GetDirectories()) {
                        ProcessFolder(db, drive, arrHeaders, subDirectory);
                    }
                }
                catch (Exception ex) {
                    Console.WriteLine(ex.ToString());
                }
            }
            catch (UnauthorizedAccessException) {

            }
            catch (Exception ex) {
                Console.WriteLine(ex.ToString());
            }
        }
Example #57
0
 public void                     ProcessFolder(string path)
 {
     Debug.WriteLine("    [Processing Folder " + path + "]");
     string[] files = Directory.GetFiles(path);
     foreach (string file in files)
     {
         Shell32.Shell shell = new Shell32.Shell();
         Shell32.Folder objFolder;
         objFolder = shell.NameSpace(@path);
         Shell32.FolderItem item = objFolder.ParseName(System.IO.Path.GetFileName(file));
         if (System.IO.Path.GetFileName(file) != "desktop.ini")
             ProcessFile(item, objFolder);
     }
     string[] subdirs = Directory.GetDirectories(path);
     foreach (string subdir in subdirs)
         ProcessFolder(subdir);
 }
Example #58
0
        public static string ReadLnk(string lnkPath)
        {
            string link = string.Empty;
            try
            {
                var shl = new Shell32.Shell();         // Move this to class scope
                lnkPath = System.IO.Path.GetFullPath(lnkPath);
                var dir = shl.NameSpace(System.IO.Path.GetDirectoryName(lnkPath));
                var itm = dir.Items().Item(System.IO.Path.GetFileName(lnkPath));
                var lnk = (Shell32.ShellLinkObject)itm.GetLink;
                link = lnk.Target.Path;
                //link = lnk.Path;

                //var x = (Shell32.FolderItem)itm.Application;
                //link = x.Application;
                /*
                FileStream fileStream = System.IO.File.Open(lnkPath, FileMode.Open, FileAccess.Read);
                using (System.IO.BinaryReader fileReader = new BinaryReader(fileStream))
                {
                    fileStream.Seek(0x14, SeekOrigin.Begin);     // Seek to flags
                    uint flags = fileReader.ReadUInt32();        // Read flags
                    if ((flags & 1) == 1)
                    {                      // Bit 1 set means we have to
                                           // skip the shell item ID list
                        fileStream.Seek(0x4c, SeekOrigin.Begin); // Seek to the end of the header
                        uint offset = fileReader.ReadUInt16();   // Read the length of the Shell item ID list
                        fileStream.Seek(offset, SeekOrigin.Current); // Seek past it (to the file locator info)
                    }

                    long fileInfoStartsAt = fileStream.Position; // Store the offset where the file info
                                                                 // structure begins
                    uint totalStructLength = fileReader.ReadUInt32(); // read the length of the whole struct
                    fileStream.Seek(0xc, SeekOrigin.Current); // seek to offset to base pathname
                    uint fileOffset = fileReader.ReadUInt32(); // read offset to base pathname
                                                               // the offset is from the beginning of the file info struct (fileInfoStartsAt)
                    fileStream.Seek((fileInfoStartsAt + fileOffset), SeekOrigin.Begin); // Seek to beginning of
                                                                                        // base pathname (target)
                    long pathLength = (totalStructLength + fileInfoStartsAt) - fileStream.Position - 2; // read
                                                                                                        // the base pathname. I don't need the 2 terminating nulls.
                    char[] linkTarget = fileReader.ReadChars((int)pathLength); // should be unicode safe
                    link = new string(linkTarget);

                    int begin = link.IndexOf("\0\0");
                    if (begin > -1)
                    {
                        int end = link.IndexOf("\\\\", begin + 2) + 2;
                        end = link.IndexOf('\0', end) + 1;

                        string firstPart = link.Substring(0, begin);
                        string secondPart = link.Substring(end);

                        link = firstPart + secondPart;
                    }
                }
                */
            }
            catch (Exception e)
            {
                WriteProgramLog("Could not read file: " + lnkPath + "\n\t Reason: " + e.Message);
                //throw new Exception(e.Message);
            }
            return link;
        }