Пример #1
0
    public static void CredentialDriveServiceByToken()
    {
        if (DriveService == null)
        {
            UserCredential credential;
            using (var stream =
                       new FileStream(credentialPath, FileMode.Open, FileAccess.Read))
            {
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new string[] { DriveService.Scope.DriveReadonly },
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Drive API service.
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });
            DriveService = service;
            DriveManager.Init(service);
        }
    }
        // GET api/<controller>
        public DriveDTO Get([FromUri] string name = "")
        {
            List <String>  FolderList    = new List <string>();
            RDirectoryItem CurrentFolder = new RDirectoryItem();

            string       FolderPath  = string.Empty;
            Member       CurrentUser = db.Members.FirstOrDefault(d => d.Email == User.Identity.Name);
            DriveManager DM          = new DriveManager(CurrentUser, System.Web.Hosting.HostingEnvironment.MapPath(Utility.SiteDriveFolderPath), string.Format("{0}/{1}", Utility.SiteURL, Utility.SiteDriveFolderName));

            DM.ItemDeletable = true;

            if (!string.IsNullOrEmpty(name))
            {
                FolderPath = name;
            }


            FolderList    = FolderPath.Split('/').ToList <string>();
            CurrentFolder = DM.GetFolderName(FolderPath);

            DriveDTO result = new DriveDTO();

            result.Crumbs.AddRange(DM.GetCrumbs(FolderPath));
            result.Directories.AddRange(DM.GetDirectoryItemList(FolderPath));
            result.Files.AddRange(DM.GetFileItemList(FolderPath));

            return(result);
        }
        public async Task <IHttpActionResult> PostAsync(string parentId = null, string mail = null, bool extract = false, CancellationToken cancellationToken = default(CancellationToken))
        {
            int userId = ApiSecurity.CurrentUserId;
            var files  = new List <FileItem>();
            var parent = await FindFileAsync(parentId, cancellationToken);

            var parenti = parent == null ? default(int?) : parent.Id;
            var manager = new DriveManager(ApiSecurity.Manager, _services, ServerPaths.Map(ServerPaths.DriveFiles));

            using (var content = await Request.Content.ReadAsFileStreamAsync(cancellationToken))
            {
                files.Add(await manager.CreateFromStreamAsync(content.FileStream, parenti, userId, content.FileName, cancellationToken));
            }

            return(Ok(ListResult.Create(files.Select(file => new FileStoreUploadResult
            {
                Name = file.Name,
                Link = new Uri(Request.RequestUri, Url.Route(PublicRootName, new RouteValueDictionary
                {
                    { "userId", file.OwnerId },
                    { "path", file.PhysicalPath }
                }))
                       .AbsoluteUri
            }))));
        }
Пример #4
0
        private IEnumerable<DispatchItem> GetDispatchDestinations()
        {
            List<DispatchItem> destinations = new List<DispatchItem>();

            if (player.ActionCounter.Count == 0)
                return destinations;

            foreach (Player player in players)
            {

                DriveManager dm = new DriveManager(player);
                foreach (DriveDestinationItem ddi in dm.GetDestinations(this.player.ActionCounter.Count))
                {
                    if (ddi.Node.Players.Count() == 0)
                        destinations.Add(new DispatchItem(player, ddi.Node, ddi.Cost));
                }

                foreach (Player sub in players)
                {
                    if (sub.Location != player.Location && destinations.Where(i => i.Player == player && i.DispatchDestination == sub.Location).Count() == 0)
                        destinations.Add(new DispatchItem(player, sub.Location, 1));
                }
            }

            return destinations;
        }
Пример #5
0
        public JsonResult Get()
        {
            var listAll = DriveManager.GetAllDrives();

            Response.StatusCode = (int)HttpStatusCode.OK;
            return(Json(listAll));
        }
Пример #6
0
        private IEnumerable <DispatchItem> GetDispatchDestinations()
        {
            List <DispatchItem> destinations = new List <DispatchItem>();

            if (player.ActionCounter.Count == 0)
            {
                return(destinations);
            }

            foreach (Player player in players)
            {
                DriveManager dm = new DriveManager(player);
                foreach (DriveDestinationItem ddi in dm.GetDestinations(this.player.ActionCounter.Count))
                {
                    if (ddi.Node.Players.Count() == 0)
                    {
                        destinations.Add(new DispatchItem(player, ddi.Node, ddi.Cost));
                    }
                }

                foreach (Player sub in players)
                {
                    if (sub.Location != player.Location && destinations.Where(i => i.Player == player && i.DispatchDestination == sub.Location).Count() == 0)
                    {
                        destinations.Add(new DispatchItem(player, sub.Location, 1));
                    }
                }
            }

            return(destinations);
        }
Пример #7
0
        static void Main(string[] args)
        {
            List <Drive> listAll = DriveManager.GetAllDrives();

            string path               = "C:\\";
            string pathRec            = "C:\\";
            var    currentFolderItems = FolderManager.GetAllItemsForFolder(path);

            foreach (var item in listAll)
            {
                Console.WriteLine(item.Name);
            }
            Console.WriteLine("----------------------------------------------------------");

            foreach (var item in currentFolderItems)
            {
                Console.WriteLine(item.Name);
            }
            Console.WriteLine("----------------------------------------------------------");

            var items = GlobalFilesCalculation.GetFilesCount(pathRec);

            Console.WriteLine($"{items.FilesThatLessThan10Mb} -- " +
                              $"{items.FilesBetween10ANd50Mb} --" +
                              $"errors - {items.Errors} --" +
                              $"{items.FilesMoreThan100Mb}");

            Console.ReadKey();
        }
Пример #8
0
        public void GetCountOfDrivers()
        {
            List <Drive> drives     = new List <Drive>();
            int          countDrive = 6;

            drives = DriveManager.GetAllDrives();

            Assert.That(drives.Count, Is.EqualTo(countDrive));
        }
Пример #9
0
        public void GetSizeForC()
        {
            List <Drive> drives    = new List <Drive>();
            long         diskCsize = 195;

            drives = DriveManager.GetAllDrives();
            long diskC = drives.Where(c => c.Name == "C:\\").First().TotalSize;

            Assert.That(diskCsize, Is.EqualTo(diskC));
        }
Пример #10
0
        public void GetCountForInanctiveDrives()
        {
            List <Drive> drives         = new List <Drive>();
            int          inactiveDrives = 2;

            drives = DriveManager.GetAllDrives();
            int inactDrives = drives.Where(c => c.IsReady == false).ToList().Count;

            Assert.That(inactiveDrives, Is.EqualTo(inactDrives));
        }
Пример #11
0
        private void ShowTreeDisks()
        {
            ComputerMenuItem comp = new ComputerMenuItem();
            //trvMenu.Items.Add(comp);
            Dictionary <string, DriveInfo> disks = DriveManager.GetDrives();

            foreach (var item in disks)
            {
                ShowTreeItems(item.Key);
            }
        }
Пример #12
0
        public void CheckSorting()
        {
            List <Drive> drives = new List <Drive>();
            bool         firstSizeMoreThanLast = true;

            drives = DriveManager.GetAllDrives();
            var  firstDrive = drives[0];
            var  lastDrive  = drives[drives.Count - 1];
            bool checkSize  = firstDrive.TotalSize > lastDrive.TotalSize;

            Assert.That(firstSizeMoreThanLast, Is.EqualTo(checkSize));
        }
Пример #13
0
        private bool format_device(string drive_letter, string model_id, string file_system = "FAT", bool quick_format = false, int cluster_size = 2048)
        {
            bool   bReturn     = false;
            string err_message = "";

            Application.Current.Dispatcher.Invoke(() => {
                prgbFormat.Visibility = Visibility.Visible;
                prgbUpgradeText.Text  = string.Format("Formatting...      ");
                prgbUpgrade.Maximum   = 100;
                prgbUpgrade.Value     = 0;
            });

            try
            {
                DriveManager dm = new DriveManager();


                dm.FormatUSBProgress  += Dm_FormatUSBProgress;
                dm.FormatUSBCompleted += Dm_FormatUSBCompleted;
                bReturn = dm.FormatUSB(drive_letter, file_system, quick_format, cluster_size, model_id);

                /*
                 * dm.FormatDriveCompleted += Dm_FormatUSBCompleted;
                 * bReturn = dm.FormatDrive_CommandLine(drive_letter, model_id, file_system, quick_format, false, cluster_size);
                 */
            }
            catch (FormatException e)
            {
                err_message = e.Message;
            }
            catch (IOException e)
            {
                err_message = e.Message;
            }
            catch (Exception e)
            {
                err_message = e.Message;
            }

            if (err_message != "")
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    prgbFormat.Visibility = Visibility.Hidden;
                    prgbUpgradeText.Text  = err_message;
                    prgbUpgrade.Maximum   = 100;
                    prgbUpgrade.Value     = 0;
                });
            }

            return(bReturn);
        }
Пример #14
0
        public void UpdateDriveAvailable()
        {
            List <string> listOfAvailableDrive = new List <string>();

            while (!_stopThread)
            {
                if (listOfAvailableDrive.Count != DriveManager.GetAllDrive().Count)
                {
                    listOfAvailableDrive = DriveManager.GetAllDrive();
                    DriveLetter          = new ObservableCollection <string>(listOfAvailableDrive);
                }
                Thread.Sleep(100);
            }
        }
Пример #15
0
 public void OnDriveChanged(DriveManager driveManager)
 {
     if (driveManager.CurrDriveMode == DriveManager.DriveMode.Charging)
     {
         innerFillCharge.enabled = true;
         innerFillSummon.enabled = false;
     }
     else if (driveManager.CurrDriveMode == DriveManager.DriveMode.Summon)
     {
         innerFillCharge.enabled = false;
         innerFillSummon.enabled = true;
     }
     OnDriveChanged(driveManager.MaxDrive, driveManager.CurrDrive, driveManager.MaxCharge, driveManager.CurrCharge);
 }
Пример #16
0
        private string RegistryAddress;  // defaults to null


        ////////////////////////////////////////////////////////


        public FlabberManager()
        {
            // get token
            MyLoginManager = new LoginManager();
            Token          = MyLoginManager.GetToken();

            // check user
            MyDriveManager = new DriveManager(Token);
            Me             = MyDriveManager.GetMe().GetAwaiter().GetResult();
            if (!MyLoginManager.IsAllowed(Me))
            {
                throw new Exception("User not allowed");
            }

            MyEthManager = new EthManager();
        }
Пример #17
0
        public async Task <IHttpActionResult> PostAsync([FromBody] FileItem model, CancellationToken cancellationToken)
        {
            ModelState.Remove("model.Slug");
            if (model == null || !ModelState.IsValid)
            {
                return(BadRequest());
            }

            var manager = new DriveManager(ApiSecurity.Manager, _services, ServerPaths.Map(ServerPaths.DriveFiles));

            model = await manager.CreateAsync(model, ApiSecurity.CurrentUserId, cancellationToken);

            return(CreatedAtRoute(GetByIdRouteName, new RouteValueDictionary {
                { "id", model.Id }
            }, model));
        }
Пример #18
0
        private bool format_device(string drive_letter)
        {
            bool bReturn = false;

            Application.Current.Dispatcher.Invoke(() => {
                prgbFormat.Visibility = Visibility.Visible;
                prgbUpgradeText.Text  = string.Format("Formatting...      ");
                prgbUpgrade.Maximum   = 100;
                prgbUpgrade.Value     = 0;
            });

            try
            {
                DriveManager dm = new DriveManager();
                // bReturn = dm.FormatDrive(char.Parse(drive_letter.Replace(":","")));

                dm.FormatUSBProgress  += Dm_FormatUSBProgress;
                dm.FormatUSBCompleted += Dm_FormatUSBCompleted;
                bReturn = dm.FormatUSB(drive_letter);
            }
            catch (FormatException e)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    prgbUpgradeText.Text = e.Message;
                    prgbUpgrade.Maximum  = 100;
                    prgbUpgrade.Value    = 0;
                });
            }
            catch (IOException e)
            {
                Application.Current.Dispatcher.Invoke(() => {
                    prgbUpgradeText.Text = e.Message;
                    prgbUpgrade.Maximum  = 100;
                    prgbUpgrade.Value    = 0;
                });
            }
            catch (Exception e)
            {
                Application.Current.Dispatcher.Invoke(() => {
                    prgbUpgradeText.Text = e.Message;
                    prgbUpgrade.Maximum  = 100;
                    prgbUpgrade.Value    = 0;
                });
            }
            return(bReturn);
        }
Пример #19
0
// ReSharper restore RedundantAssignment
        /// <summary>
        /// Locates Windows system windows, like TaskBar and locates Power8 MainButton inside it.
        /// Starts location update thread. Subscribes to Settings Manager events and registers HotKey.
        /// </summary>
        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            _taskBar = API.FindWindow(API.WndIds.TRAY_WND_CLASS, null);
            CheckWnd(_taskBar, API.WndIds.TRAY_WND_CLASS);
            SystemScale = 1f / 96;
            using (var g = Graphics.FromHwnd(_taskBar))
            {
                SystemScale *= g.DpiX;
            }

            if (Util.OsIs.SevenOrMore && !Util.OsIs.TenOrMore) //7 --> 8.1
            {
                _midPanel = API.FindWindowEx(_taskBar, IntPtr.Zero, API.WndIds.TRAY_REBAR_WND_CLASS, null);
                CheckWnd(_midPanel, API.WndIds.TRAY_REBAR_WND_CLASS);
                if (Util.OsIs.EightBlueOrMore)
                {
                    _startBtn = API.FindWindowEx(_taskBar, IntPtr.Zero, API.WndIds.SH_W8_1_START_CLASS, null);
                    CheckWnd(_startBtn, API.WndIds.SH_W8_1_START_CLASS);
                }
                _showDesktopBtn = API.FindWindowEx(_taskBar, IntPtr.Zero, API.WndIds.TRAY_NTF_WND_CLASS, null);
                CheckWnd(_showDesktopBtn, API.WndIds.TRAY_NTF_WND_CLASS);
                _showDesktopBtn = API.FindWindowEx(_showDesktopBtn, IntPtr.Zero, API.WndIds.SH_DSKTP_WND_CLASS, null);
                CheckWnd(_showDesktopBtn, API.WndIds.SH_DSKTP_WND_CLASS);
            }
            else //XP, 10
            {
                var hostClass = Util.OsIs.TenOrMore ? API.WndIds.SH_W8_1_START_CLASS : API.WndIds.SH_DSKTP_START_CLASS;
                _showDesktopBtn = API.FindWindowEx(_taskBar, IntPtr.Zero, hostClass, null);
                CheckWnd(_showDesktopBtn, hostClass);
            }

            Left = 0;
            Top  = 0;
            SetParent(this.MakeGlassWpfWindow());
            Util.ForkStart(WatchDesktopBtn, "ShowDesktop button watcher");

            //Register as a HWND that will be used as device notification processor proxy by DriveManager
            DriveManager.SetReporter(this.GetHandle());

            SettingsManager.WarnMayHaveChanged += SettingsManagerOnWarnMayHaveChanged;
            SettingsManager.ImageChanged       += SettingsManagerOnImageChanged;
            SettingsManager.PicStretchChanged  += SettingsManagerOnImageStretchChanged;
            SettingsManager.BgrThreadLock.Set();

            API.RegisterHotKey(this.GetHandle(), 0, API.fsModifiers.MOD_ALT, Keys.Z);
            this.RegisterHook(WndProc);
        }
Пример #20
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (CurrentUser.UserType == (byte)MemberTypeType.Admin)
            {
                DM = new DriveManager(CurrentUser, Server.MapPath(Utility.SiteDriveFolderPath),
                                      string.Format("{0}/{1}", Utility.SiteURL, Utility.SiteDriveFolderName));
                DM.ItemDeletable = true;
            }
            else if (CurrentUser.UserType == (byte)MemberTypeType.Author)
            {
                DM = new DriveManager(CurrentUser, Server.MapPath(Utility.SiteDriveFolderPath + "/" + CurrentUser.ID.ToString()),
                                      string.Format("{0}/{1}/{2}", Utility.SiteURL, Utility.SiteDriveFolderName, CurrentUser.ID.ToString()));
                DM.ItemDeletable = true;
                //check if author drive folder exists if not create one.
                DM.VerifyDrive();
            }

            if (Request.QueryString["folderpath"] != null)
            {
                FolderPath = Request.QueryString["folderpath"].ToString().Trim();
            }
            else
            {
                FolderPath = string.Empty;
            }

            FolderList    = FolderPath.Split('/').ToList <string>();
            CurrentFolder = DM.GetFolderName(FolderPath);


            FolderTableRepeater.DataSource = DM.GetDirectoryItemList(FolderPath);
            FolderTableRepeater.DataBind();
            FileItemRepeater.DataSource = DM.GetFileItemList(FolderPath);
            FileItemRepeater.DataBind();
        }
        catch (Exception ex)
        {
            message4.Text     = string.Format("Unable to process request. Error - {0}", ex.Message);
            message4.Visible  = true;
            message4.Indicate = AlertType.Error;
        }
    }
Пример #21
0
// ReSharper disable RedundantAssignment
        /// <summary> Hooks WndProc to react on HOTKEY passed (Alt+Z) </summary>
        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            handled = false;
            if (msg == (uint)API.WM.HOTKEY)
            {
                handled = true;
                if (BtnStck.IsInstantited && BtnStck.Instance.IsActive)
                {
                    Activate(); //WXP requires this
                    b1.Focus();
                }
                else if (BtnStck.IsInstantited)
                {
                    ShowButtonStack(Keyboard.PrimaryDevice, null);
                }
            }
            if (msg == (int)API.WM.DEVICECHANGE && (handled = DriveManager.HandleDeviceNotification(wParam, lParam)))
            {
                return(new IntPtr(1)); //MSDN: return true to allow request. We never deny, we just react on this.
                //WinUser.h: #define BROADCAST_QUERY_DENY         0x424D5144  // Return this value to deny a query.
            }
            return(IntPtr.Zero);
        }
Пример #22
0
        internal void SetPlayer(Player player, IEnumerable<Player> players, IEnumerable<Node> nodes, IEnumerable<NodeDiseaseCounter> nodeDiseaseCounters, ResearchStationCounter researchStationCounter, IEnumerable<Disease> diseases)
        {
            driveManager = new DriveManager(player);
            CanDrive = driveManager.CanDrive;
            Drive = driveManager.Drive;

            directFlightManager = new DirectFlightManager(player);
            CanDirectFlight = directFlightManager.CanDirectFlight;
            DirectFlight = directFlightManager.DirectFlight;

            charterFlightManager = new CharterFlightManager(player, nodes);
            CanCharterFlight = charterFlightManager.CanCharterFlight;
            CharterFlight = charterFlightManager.CharterFlight;

            shuttleFlightManager = new ShuttleFlightManager(player, nodes);
            CanShuttleFlight = shuttleFlightManager.CanShuttleFlight;
            ShuttleFlight = shuttleFlightManager.ShuttleFlight;

            researchStationConstructionManager = new ResearchStationConstructionManager(player, researchStationCounter, nodes);
            CanBuildResearchStation = researchStationConstructionManager.CanConstructResearchStation;
            BuildResearchStation = researchStationConstructionManager.ConstructResearchStation;

            treatDiseaseManager = new TreatDiseaseManager(player, nodeDiseaseCounters);
            CanTreatDisease = treatDiseaseManager.CanTreat;
            TreatDisease = treatDiseaseManager.Treat;

            shareKnowledgeManager = new ShareKnowledgeManager(player, players);
            CanShareKnowledge = shareKnowledgeManager.CanShareKnowledge;
            ShareKnowledge = shareKnowledgeManager.ShareKnowledge;

            discoverCureManager = new DiscoverCureManager(player, diseases);
            CanDiscoverCure = discoverCureManager.CanDiscoverCure;
            DiscoverCure = discoverCureManager.DiscoverCure;

            dispatchManager = new DispatchManager(player, players);
            CanDispatch = dispatchManager.CanDispatch;
            Dispatch = dispatchManager.Dispatch;

            operationsRelocationManager = new OperationsRelocationManager(player, nodes);
            CanRelocate = operationsRelocationManager.CanRelocate;
            Relocate = operationsRelocationManager.Relocate;
        }
Пример #23
0
 public bool FormatDrive(char letter)
 {
     return(DriveManager.FormatDrive(letter, "RecalboxOs", "FAT32"));
 }
Пример #24
0
 public bool CheckDrive(string driveLetter)
 {
     return(DriveManager.IsFat32(driveLetter));
 }
Пример #25
0
    public void DownloadFromSheet(string xmlPath = null)
    {
        string xmlSavePath = "";

        if (string.IsNullOrEmpty(xmlPath))
        {
            xmlSavePath = Setting.Config.XmlSavePath;
        }
        if (string.IsNullOrEmpty(xmlSavePath))
        {
            xmlSavePath = xmlPath;
        }
        if (string.IsNullOrEmpty(xmlSavePath))
        {
            Console.WriteLine("xml path is null");
            return;
        }

        System.IO.Directory.CreateDirectory(new FileInfo(xmlPath).Directory.FullName);
        System.IO.Directory.CreateDirectory(new FileInfo(Setting.Config.CSVSavePath).Directory.FullName);
        // 생성할 XML 파일 경로와 이름, 인코딩 방식을 설정합니다.
        XmlTextWriter textWriter = new XmlTextWriter(xmlSavePath, Encoding.UTF8);

        // 들여쓰기 설정
        textWriter.Formatting = System.Xml.Formatting.Indented;
        // 문서에 쓰기를 시작합니다.
        textWriter.WriteStartDocument();
        textWriter.WriteStartElement("base");
        textWriter.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        textWriter.WriteAttributeString("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
        textWriter.WriteAttributeString("type", "string");
        textWriter.WriteStartElement("tags");
        textWriter.WriteStartElement("tag");
        textWriter.WriteAttributeString("language", "한국어");
        textWriter.WriteEndElement();
        textWriter.WriteEndElement();
        textWriter.WriteStartElement("strings");
        var csv = DriveManager.DownloadCSV("1oY5F5P-tMBj1-kryB5gR4gS4T5KrlqmDc-tHQBrQBDo");

        System.IO.File.WriteAllText(Setting.Config.CSVSavePath, csv);
        var splitnl = csv.Split('\n');

        using (var reader = new StreamReader(Setting.Config.CSVSavePath))
        {
            using (var td = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                var records = td.GetRecords <TranslateData>();
                foreach (var record in records)
                {
                    textWriter.WriteStartElement("string");
                    textWriter.WriteAttributeString("id", record.Id);
                    var translateText = record.Translate;
                    translateText = translateText.Replace("\\n", "\n");
                    textWriter.WriteAttributeString("text", translateText);
                    textWriter.WriteEndElement();
                }
            }
        }
        textWriter.WriteEndElement();
        textWriter.WriteEndElement();
        textWriter.WriteEndDocument();
        textWriter.Close();
    }
Пример #26
0
        public void process(ulong total, bool proverka)
        {
            /*nabor.progress.Refresh();
             * nabor.progress.CreateGraphics().DrawString("asfdsdgsdg",
             *  new Font("Arial", (float)8.25, FontStyle.Regular),
             *  Brushes.Black, new PointF(nabor.progress.Width / 2 - 10,
             *      nabor.progress.Height / 2 - 7));*/
            this.proverka = proverka;
            this.total    = total;
            bool proveril = false;

            try
            {
                if ((ulong)drive.TotalSize < total)
                {
                    if (nabor.status.InvokeRequired)
                    {
                        nabor.status.Invoke(new Action <string>((s) => nabor.status.Text = s), "Недостаточно места на флешке. ");
                    }
                    else
                    {
                        nabor.status.Text = "Недостаточно места на флешке. ";
                    }
                    proveril = true;
                    fail(this);
                    return;
                }
            }
            catch
            {
                if (nabor.status.InvokeRequired)
                {
                    nabor.status.Invoke(new Action <string>((s) => nabor.status.Text = s), "Не удалось определить объём флешки. ");
                }
                else
                {
                    nabor.status.Text = "Не удалось определить объём флешки. ";
                }
            }
            try
            {
                Process prc = new Process();
                //prc.Exited += Prc_Exited; ;
                new Thread(() => {
                    try
                    {
                        if (Directory.GetFiles(drive.RootDirectory.FullName).Length == 0 & Directory.GetDirectories(drive.RootDirectory.FullName).Length == 0)
                        {
                            if (nabor.status.InvokeRequired)
                            {
                                nabor.status.Invoke(new Action <string>((s) => nabor.status.Text = s), "Переименование. ");
                            }
                            else
                            {
                                nabor.status.Text = "Переименование. ";
                            }
                            if (!DriveManager.RenameDrive(prc, drive.Name[0], labelt))
                            {
                                if (nabor.status.InvokeRequired)
                                {
                                    nabor.status.Invoke(new Action <string>((s) => nabor.status.Text = s), "Ошибка при попытке форматировать. ");
                                }
                                else
                                {
                                    nabor.status.Text = "Ошибка при попытке форматировать. ";
                                }
                                throw new Exception();
                            }
                        }
                        else
                        {
                            if (nabor.status.InvokeRequired)
                            {
                                nabor.status.Invoke(new Action <string>((s) => nabor.status.Text = s), "Форматирование. ");
                            }
                            else
                            {
                                nabor.status.Text = "Форматирование. ";
                            }
                            if (!DriveManager.FormatDrive(prc, drive.Name[0], labelt, "FAT32"))
                            {
                                if (nabor.status.InvokeRequired)
                                {
                                    nabor.status.Invoke(new Action <string>((s) => nabor.status.Text = s), "Ошибка при попытке форматировать. ");
                                }
                                else
                                {
                                    nabor.status.Text = "Ошибка при попытке форматировать. ";
                                }
                                throw new Exception();
                            }
                        }

                        /*}
                         * catch (Exception e)
                         * {
                         *  if (nabor.status.InvokeRequired) nabor.status.Invoke(new Action<string>((s) => nabor.status.Text = "Ошибка при попытке форматировать. " + s), e.Message);
                         *  else nabor.status.Text = "Ошибка при попытке форматировать. " + e.Message;
                         *  fail(this);
                         *  Thread.CurrentThread.Abort();
                         *  return;
                         * }
                         * try { */
                        if ((ulong)drive.AvailableFreeSpace < total && proveril == false)
                        {
                            if (nabor.status.InvokeRequired)
                            {
                                nabor.status.Invoke(new Action <string>((s) => nabor.status.Text = s), "Недостаточно места на флешке. ");
                            }
                            else
                            {
                                nabor.status.Text = "Недостаточно места на флешке. ";
                            }
                            proveril = true;
                            fail(this);
                            Thread.CurrentThread.Abort();
                            return;
                        }
                    }
                    catch (Exception e)
                    {
                        if (nabor.status.InvokeRequired)
                        {
                            nabor.status.Invoke(new Action <string>((s) => nabor.status.Text = "Не читается. " + s), e.Message);
                        }
                        else
                        {
                            nabor.status.Text = "Не читается. " + e.Message;
                        }
                        fail(this);
                        Thread.CurrentThread.Abort();
                        return;
                    }
                    //fail(this);
                    try { Prc_Exited(); }
                    catch (Exception e) {
                        if (nabor.status.InvokeRequired)
                        {
                            nabor.status.Invoke(new Action <string>((s) => nabor.status.Text = "Ошибка при попытке копирования. " + s), e.Message);
                        }
                        else
                        {
                            nabor.status.Text = "Ошибка при попытке копирования. " + e.Message;
                        }
                        fail(this);
                        Thread.CurrentThread.Abort();
                        return;
                    }
                }).Start();            // Выполнить в новом потоке
            }
            catch (Exception e)
            {
                if (nabor.status.InvokeRequired)
                {
                    nabor.status.Invoke(new Action <string>((s) => nabor.status.Text += s), e.Message);
                }
                else
                {
                    nabor.status.Text += e.Message;
                }
                fail(this);
                Thread.CurrentThread.Abort();
                return;
            }
        }
Пример #27
0
 public MainWindowViewModel()
 {
     Drives = new ObservableCollection <DriveInfo>(DriveManager.GetAllDrives());
 }
Пример #28
0
 private void RefreshDrives()
 {
     Drives = DriveManager.GetDrives();
 }