CopyTo() публичный Метод

public CopyTo ( string array, int index ) : void
array string
index int
Результат void
Пример #1
0
        /// http://jeanne.wankuma.com/tips/csharp/directory/getfilesmostdeep.html
        /// ---------------------------------------------------------------------------------------
        /// <summary>
        ///     指定した検索パターンに一致するファイルを最下層まで検索しすべて返します。</summary>
        /// <param name="stRootPath">
        ///     検索を開始する最上層のディレクトリへのパス。</param>
        /// <param name="stPattern">
        ///     パス内のファイル名と対応させる検索文字列。</param>
        /// <returns>
        ///     検索パターンに一致したすべてのファイルパス。</returns>
        /// ---------------------------------------------------------------------------------------
        public static string[] GetFilesMostDeep(string stRootPath, string stPattern)
        {
            // ファイルリスト取得開始をデバッグ出力
            Debug.Print(DateTime.Now + " Started to get files recursivery.");

            StringCollection hStringCollection = new StringCollection();

            // このディレクトリ内のすべてのファイルを検索する
            foreach (string stFilePath in Directory.GetFiles(stRootPath, stPattern))
            {
                hStringCollection.Add(stFilePath);
                Debug.Print(DateTime.Now + " Found image file, Filename = " + stFilePath);
            }

            // このディレクトリ内のすべてのサブディレクトリを検索する (再帰)
            foreach (string stDirPath in Directory.GetDirectories(stRootPath))
            {
                string[] stFilePathes = GetFilesMostDeep(stDirPath, stPattern);

                // 条件に合致したファイルがあった場合は、ArrayList に加える
                if (stFilePathes != null)
                {
                    hStringCollection.AddRange(stFilePathes);
                }
            }

            // StringCollection を 1 次元の String 配列にして返す
            string[] stReturns = new string[hStringCollection.Count];
            hStringCollection.CopyTo(stReturns, 0);

            // ファイルリスト取得終了をデバッグ出力
            Debug.Print(DateTime.Now + " Finished to get files recursivery.");

            return stReturns;
        }
 static void Main(string[] args)
 {
     System.Collections.Specialized.StringCollection stringCollection = new System.Collections.Specialized.StringCollection();
     String[] Cities = new String[] { "Hyderabad", "Delhi", "Mumbai", "Banglore", "Chennai", "Kolkatta" };
     stringCollection.AddRange(Cities);
     // Display the contents of the collection using foreach.
     Console.WriteLine("Displays the elements using foreach:");
     foreach (String obj in stringCollection)
     {
         Console.WriteLine("   {0}", obj);
     }
     Console.WriteLine();
     stringCollection.Add("Pune");
     stringCollection.Add("Vizag");
     stringCollection.Remove("Chennai");
     Console.WriteLine("After Updating Collection:");
     foreach (String obj in stringCollection)
     {
         Console.WriteLine("   {0}", obj);
     }
     Console.WriteLine();
     // Copy the collection to a new array starting at index 0.
     String[] CitiesArray = new String[stringCollection.Count];
     stringCollection.CopyTo(CitiesArray, 0);
     Console.WriteLine("The new array contains:");
     for (int i = 0; i < CitiesArray.Length; i++)
     {
         Console.WriteLine("   [{0}] {1}", i, CitiesArray[i]);
     }
     Console.WriteLine();
     Console.ReadLine();
 }
Пример #3
0
 internal IEnumerable<FlagTokens> GetTokens(string[] args)
 {
     StringCollection rest = new StringCollection();
     for (int i = 0; i < args.Length; i++)
     {
         var arg = args[i];
         if (arg.StartsWith("/"))
         {
             FlagTokens tok = new FlagTokens();
             tok.flag = arg;
             tok.args = null;
             int flagArgsStart = arg.IndexOf(':');
             if (flagArgsStart > 0)
             {
                 tok.flag = arg.Substring(0, flagArgsStart);
                 tok.args = arg.Substring(flagArgsStart+1).Split(';');
             }
             yield return tok;
         }
         else
         {
             rest.Add(arg);
         }
     }
     if (rest.Count > 0)
     {
         FlagTokens tok = new FlagTokens();
         tok.flag = null;
         tok.args = new string[rest.Count];
         rest.CopyTo(tok.args, 0);
         yield return tok;
     }
     yield break;
 }
        string[,] ReadFile(string fileName)
        {
            try {
                var sc = new StringCollection ();
                var fs = new FileStream (fileName, FileMode.Open, FileAccess.ReadWrite);
                var sr = new StreamReader (fs);

                // Read file into a string collection
                int noBytesRead = 0;
                string oneLine;
                while ((oneLine = sr.ReadLine()) != null) {
                    noBytesRead += oneLine.Length;
                    sc.Add (oneLine);
                }
                sr.Close ();

                string[] sArray = new string[sc.Count];
                sc.CopyTo (sArray, 0);

                char[] cSplitter = { ' ', ',', ':', '\t' };
                string[] sArray1 = sArray [0].Split (cSplitter);
                string[,] sArray2 = new string[sArray1.Length, sc.Count];

                for (int i = 0; i < sc.Count; i++) {
                    sArray1 = sArray [sc.Count - 1 - i].Split (cSplitter);
                    for (int j = 0; j < sArray1.Length; j++) {
                        sArray2 [j, i] = sArray1 [j];
                    }
                }
                return sArray2;
            } catch (Exception) {
                return null;
            }
        }
 private static string[] ParseMultiValue(string value)
 {
     StringCollection strings = new StringCollection();
     bool flag = false;
     int length = 0;
     char[] chArray = new char[value.Length];
     for (int i = 0; i < value.Length; i++)
     {
         if (value[i] == '"')
         {
             flag = !flag;
         }
         else if ((value[i] == ',') && !flag)
         {
             string str = new string(chArray, 0, length);
             strings.Add(str.Trim());
             length = 0;
             continue;
         }
         chArray[length++] = value[i];
     }
     if (length != 0)
     {
         strings.Add(new string(chArray, 0, length).Trim());
     }
     string[] array = new string[strings.Count];
     strings.CopyTo(array, 0);
     return array;
 }
Пример #6
0
    // We represent the ILasm document as a set of lines. This makes it easier to manipulate it
    // (particularly to inject snippets)

    // Create a new ildocument for the given module.
    public ILDocument(string pathModule)
    {
      // ILDasm the file to produce a textual IL file.
      //   /linenum  tells ildasm to preserve line-number information. This is needed so that we don't lose
      // the source-info when we round-trip the il.

      var pathTempIl = Path.GetTempFileName();

      // We need to invoke ildasm, which is in the sdk. 
      var pathIldasm = Program.SdkDir + "ildasm.exe";

      // We'd like to use File.Exists to make sure ildasm is available, but that function appears broken.
      // It doesn't allow spaces in the filenam, even if quoted. Perhaps just a beta 1 bug.
      
      Util.Run(pathIldasm, "\"" + pathModule + "\" /linenum /text /nobar /out=\"" + pathTempIl + "\"");


      // Now read the temporary file into a string list.
      var temp = new StringCollection();
      using (TextReader reader = new StreamReader(new FileStream(pathTempIl, FileMode.Open)))
      {
        string line;
        while ((line = reader.ReadLine()) != null) {
          // Remove .maxstack since the inline IL will very likely increase stack size.
          if (line.Trim().StartsWith(".maxstack"))
            line = "// removed .maxstack declaration";

          temp.Add(line);
        }
      }
      Lines = new string[temp.Count];
      temp.CopyTo(Lines, 0);
    }
Пример #7
0
        /// <summary>
        /// http://weblogs.asp.net/jgalloway/archive/2005/09/27/426087.aspx
        /// </summary>
        public static List<string> SplitCamelCase(this string source)
        {
            if (source == null)
                return new List<string> { }; //Return empty array.

            if (source.Length == 0)
                return new List<string> { "" };

            StringCollection words = new StringCollection();
            int wordStartIndex = 0;

            char[] letters = source.ToCharArray();
            // Skip the first letter. we don't care what case it is.
            for (int i = 1; i < letters.Length; i++)
            {
                if (char.IsUpper(letters[i]))
                {
                    //Grab everything before the current index.
                    words.Add(new String(letters, wordStartIndex, i - wordStartIndex));
                    wordStartIndex = i;
                }
            }

            //We need to have the last word.
            words.Add(new String(letters, wordStartIndex, letters.Length - wordStartIndex));

            //Copy to a string array.
            string[] wordArray = new string[words.Count];
            words.CopyTo(wordArray, 0);

            List<string> stringList = new List<string>();
            stringList.AddRange(wordArray);
            return stringList;
        }
        //
        // <



        private static string[] ParseMultiValue(string value) {
            StringCollection tempStringCollection = new StringCollection();

            bool inquote = false;
            int chIndex = 0;
            char[] vp = new char[value.Length];
            string singleValue;

            for (int i = 0; i < value.Length; i++) {
                if (value[i] == '\"') {
                    inquote = !inquote;
                }
                else if ((value[i] == ',') && !inquote) {
                    singleValue = new string(vp, 0, chIndex);
                    tempStringCollection.Add(singleValue.Trim());
                    chIndex = 0;
                    continue;
                }
                vp[chIndex++] = value[i];
            }

            //
            // Now add the last of the header values to the stringtable.
            //

            if (chIndex != 0) {
                singleValue = new string(vp, 0, chIndex);
                tempStringCollection.Add(singleValue.Trim());
            }

            string[] stringArray = new string[tempStringCollection.Count];
            tempStringCollection.CopyTo(stringArray, 0) ;
            return stringArray;
        }
        public static string[] ParseStringLines(string text, string commentIndicator = "#")
        {
            string[] stringLines = text.Split('\n');
            StringCollection stringCollection = new StringCollection();

            foreach (string line in stringLines)
            {
                string newLine = line.Trim();

                if (line.Contains(commentIndicator))
                {
                    string[] splitLine = line.Split(new[] { commentIndicator }, StringSplitOptions.None);
                    newLine = splitLine[0];
                }

                if (newLine.Trim().Length > 0 && validateTunnelString.IsMatch(newLine.Trim()))
                {
                    stringCollection.Add(newLine.Trim());
                }
            }

            string[] returnValue = new string[stringCollection.Count];

            stringCollection.CopyTo(returnValue, 0);

            return returnValue;
        }
Пример #10
0
        public static string[] SplitUpperCase(this string source)
        {
            if (source == null)
                return new string[] {}; //Return empty array.

            if (source.Length == 0)
                return new[] {""};

            var words = new StringCollection();
            int wordStartIndex = 0;

            char[] letters = source.ToCharArray();
            char previousChar = char.MinValue;
            // Skip the first letter. we don't care what case it is.
            for (int i = 1; i < letters.Length; i++)
            {
                if (char.IsUpper(letters[i]) && !char.IsWhiteSpace(previousChar))
                {
                    //Grab everything before the current index.
                    words.Add(new String(letters, wordStartIndex, i - wordStartIndex));
                    wordStartIndex = i;
                }
                previousChar = letters[i];
            }
            //We need to have the last word.
            words.Add(new String(letters, wordStartIndex, letters.Length - wordStartIndex));

            //Copy to a string array.
            var wordArray = new string[words.Count];
            words.CopyTo(wordArray, 0);
            return wordArray;
        }
Пример #11
0
		protected void Page_Load(object sender, EventArgs e)
		{
			// Initialise data table to hold test results
			m_results.Columns.Add("test");
			m_results.Columns.Add("result");
            m_results.Columns.Add("time");
			m_results.Columns.Add("message");
			m_results.Columns.Add("class");

			// Initialise controls
			lblResult.Text = "";
			ltlStats.Text = "";

			// Initialise NUnit
			CoreExtensions.Host.InitializeService();

			// Find tests in current assembly
			TestPackage package = new TestPackage(Assembly.GetExecutingAssembly().Location);
			m_testSuite = new TestSuiteBuilder().Build(package);

			if (!IsPostBack)
			{
				// Display category filters
				StringCollection coll = new StringCollection();
				GetCategories((TestSuite)m_testSuite, coll);
				string[] cats = new string[coll.Count];
				coll.CopyTo(cats, 0);
				Array.Sort(cats);
				cblCategories.DataSource = cats;
				cblCategories.DataBind();
			}
		}
Пример #12
0
        public static String[] CollectionToArray(StringCollection Collection)
        {
            String[] destination = new String[Collection.Count];

            Collection.CopyTo(destination, 0);

            return destination;
        }
Пример #13
0
 /// <summary>
 /// Creates a shallow copy of the specified <see cref="StringCollection" />.
 /// </summary>
 /// <param name="stringCollection">The <see cref="StringCollection" /> that should be copied.</param>
 /// <returns>
 /// A shallow copy of the specified <see cref="StringCollection" />.
 /// </returns>
 public static StringCollection Clone(StringCollection stringCollection)
 {
     string[] strings = new string[stringCollection.Count];
     stringCollection.CopyTo(strings, 0);
     StringCollection clone = new StringCollection();
     clone.AddRange(strings);
     return clone;
 }
Пример #14
0
        private string[] ToArray(StringCollection list, string[] defaultValue)
        {
            if(list == null)
                return defaultValue;

            string[] array = new string[list.Count];
            list.CopyTo(array, 0);
            return array;
        }
Пример #15
0
 /// <summary>
 /// Initializes a RecordingPlanModel form a RecordingConfig object and a list of strings with the basic movements
 /// Moreover, the RecordingPLanModel will subscribe to the events generated by the RecordingConfig object
 /// To update the view when required
 /// </summary>
 /// <param name="recordingConfig"></param>
 /// <param name="basicMovements"></param>
 public RecordingPlanViewModel(RecordingConfig recordingConfig, StringCollection basicMovements)
 {
     _recordingConfig = recordingConfig;
     recordingConfig.PropertyChanged += recordingConfig_PropertyChanged;
     _basicMovements = new string[basicMovements.Count];
     basicMovements.CopyTo(_basicMovements, 0);
     placeholderBitmap = Convert((Bitmap)Properties.Resources.ResourceManager.GetObject("nofoto"));
     completedBitmap = Convert((Bitmap)Properties.Resources.ResourceManager.GetObject("ok"));
     SetSelectedItem(-1);
 }
Пример #16
0
        /// <summary>
        /// Creates a relative path from one file or folder to another.
        /// </summary>
        /// <param name="fromDirectory">Contains the directory that defines the start of the relative path.</param>
        /// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param>
        /// <returns>The relative path from the start directory to the end path.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static string RelativePathTo(string fromDirectory, string toPath)
        {
            if (fromDirectory == null)
                throw new ArgumentNullException("fromDirectory");

            if (toPath == null)
                throw new ArgumentNullException("toPath");

            bool isRooted = Path.IsPathRooted(fromDirectory) && Path.IsPathRooted(toPath);
            if (isRooted)
            {
                bool isDifferentRoot = string.Compare(Path.GetPathRoot(fromDirectory),
                                                     Path.GetPathRoot(toPath), true) != 0;
                if (isDifferentRoot)
                    return toPath;                          
            }                
            
            StringCollection relativePath = new StringCollection();
            string[] fromDirectories = fromDirectory.Split(Path.DirectorySeparatorChar);
            string[] toDirectories = toPath.Split(Path.DirectorySeparatorChar);

            int length = Math.Min(fromDirectories.Length, toDirectories.Length);
            int lastCommonRoot = -1;

            // find common root
            for (int x = 0; x < length; x++)
            {
                if (string.Compare(fromDirectories[x], toDirectories[x], true) != 0)
                    break;

                lastCommonRoot = x;
            }
            if (lastCommonRoot == -1)
                return toPath;
            
            // add relative folders in from path
            for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++)
                if (fromDirectories[x].Length > 0)
                    relativePath.Add("..");

            // add to folders to path
            for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++)
                relativePath.Add(toDirectories[x]);

            // create relative path
            string[] relativeParts = new string[relativePath.Count];
            relativePath.CopyTo(relativeParts, 0);

            string newPath = string.Join(Path.DirectorySeparatorChar.ToString(), relativeParts);

            return newPath;
        }
Пример #17
0
        /// <summary>
        /// Runs a single testcase.
        /// </summary>
        /// <param name="assemblyFile">The test assembly.</param>
        /// <param name="configFile">The application configuration file for the test domain.</param>
        /// <param name="referenceAssemblies">List of files to scan for missing assembly references.</param>
        /// <returns>
        /// The result of the test.
        /// </returns>
        public TestRunner CreateRunner(FileInfo assemblyFile, FileInfo configFile, StringCollection referenceAssemblies) {
            // create test domain
            _domain = CreateDomain(assemblyFile.Directory, assemblyFile, 
                configFile);

            // assemble directories which can be probed for missing unresolved 
            // assembly references
            string[] probePaths = null;
            
            if (AppDomain.CurrentDomain.SetupInformation.PrivateBinPath != null) {
                string [] privateBinPaths = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath.Split(Path.PathSeparator);
                probePaths = new string [privateBinPaths.Length + 1];
                for (int i = 0; i < privateBinPaths.Length; i++) {
                    probePaths[i] = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                        privateBinPaths[i]);
                }
            } else {
                probePaths = new string[1];
            }

            string[] references = new string[referenceAssemblies.Count];
            referenceAssemblies.CopyTo (references, 0);

            // add base directory of current AppDomain as probe path
            probePaths [probePaths.Length - 1] = AppDomain.CurrentDomain.BaseDirectory;

            // create an instance of our custom Assembly Resolver in the target domain.
#if NET_4_0
            _domain.CreateInstanceFrom(Assembly.GetExecutingAssembly().CodeBase,
                    typeof(AssemblyResolveHandler).FullName,
                    false, 
                    BindingFlags.Public | BindingFlags.Instance,
                    null,
                    new object[] {probePaths, references},
                    CultureInfo.InvariantCulture,
                    null);
#else
            _domain.CreateInstanceFrom(Assembly.GetExecutingAssembly().CodeBase,
                    typeof(AssemblyResolveHandler).FullName,
                    false, 
                    BindingFlags.Public | BindingFlags.Instance,
                    null,
                    new object[] {probePaths, references},
                    CultureInfo.InvariantCulture,
                    null,
                    AppDomain.CurrentDomain.Evidence);
#endif
            // create testrunner
            return CreateTestRunner(_domain);
        }
Пример #18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="AStringCollection"></param>
        /// <param name="AWrapString"></param>
        /// <returns></returns>
        public static string ConvertStringCollectionToCSV(StringCollection AStringCollection, string AWrapString = "")
        {
            string csvRetVal = string.Empty;

            int sizeCollection = AStringCollection.Count;

            if (sizeCollection > 0)
            {
                string[] allStrings = new string[sizeCollection];
                AStringCollection.CopyTo(allStrings, 0);

                csvRetVal = AWrapString + String.Join(AWrapString + ", " + AWrapString, allStrings) + AWrapString;
            }

            return csvRetVal;
        }
Пример #19
0
		protected void RunClick(object sender, EventArgs args)
		{
			// Determine if any category filters have been selected
			StringCollection categories = new StringCollection();
			for (int i = 0; i < cblCategories.Items.Count; i++)
			{
				if (cblCategories.Items[i].Selected)
					categories.Add(cblCategories.Items[i].Value);
			}

            if (categories.Count == 0)
            {
                for (int i = 0; i < cblCategories.Items.Count; i++)
                {
                    categories.Add(cblCategories.Items[i].Value);
                }
            }

			string[] arCats = new string[categories.Count];
			categories.CopyTo(arCats, 0);

			// Create a category filter
			ITestFilter filter = new CategoryFilter(arCats);
			TestResult result = null;

            result = m_testSuite.Run(this, filter);

			// Bind results to presentation
			gvResults.DataSource = m_results;
			gvResults.DataBind();

			// Display statistics
			ltlStats.Text = string.Format("{0} out of {1} tests run in {2} seconds.", m_executedCount, result.Test.TestCount, result.Time);

			if (m_failedCount > 0)
				ltlStats.Text += string.Format("<br/>{0} {1} failed", m_failedCount, m_failedCount == 1 ? "test" : "tests");

			int skipped = result.Test.TestCount - m_executedCount;
			if (skipped > 0)
				ltlStats.Text += string.Format("<br/>{0} {1} skipped", skipped, skipped == 1 ? "test" : "tests");

			lblResult.Text = "Suite " + (result.IsSuccess ? "Passed" : "Failed");
			if (result.IsSuccess)
				lblResult.CssClass = "passLabel";
			else
				lblResult.CssClass = "failLabel";
		}
Пример #20
0
        public string[] GetRolesForUser(string username)
        {
            var cmd = new SqlCommand("dbo.aspnet_UsersInRoles_GetRolesForUser", Holder.Connection);
            var p = new SqlParameter("@ReturnValue", SqlDbType.Int);
            SqlDataReader reader = null;
            var sc = new StringCollection();

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandTimeout = CommandTimeout;

            p.Direction = ParameterDirection.ReturnValue;
            cmd.Parameters.Add(p);
            cmd.Parameters.Add(DataProviderHelper.CreateInputParam("@ApplicationName", SqlDbType.NVarChar,
                                                                   ApplicationName));
            cmd.Parameters.Add(DataProviderHelper.CreateInputParam("@UserName", SqlDbType.NVarChar, username));
            try
            {
                reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
                while (reader.Read())
                    sc.Add(reader.GetString(0));
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
            if (sc.Count > 0)
            {
                var strReturn = new String[sc.Count];
                sc.CopyTo(strReturn, 0);
                return strReturn;
            }

            switch (DataProviderHelper.GetReturnValue(cmd))
            {
                case 0:
                    return new string[0];
                case 1:
                    return new string[0];
                    //throw new ProviderException(SR.GetString(SR.Provider_user_not_found));
                default:
                    throw new ProviderException(StringResources.GetString(StringResources.ProviderUnknownFailure));
            }
        }
Пример #21
0
    /// <summary>
    /// Evaulate the path string in relation to the current item
    /// </summary>
    /// <param name="context">The Revolver context to evaluate the path against</param>
    /// <param name="path">The path to evaulate. Can either be absolute or relative</param>
    /// <returns>The full sitecore path to the target item</returns>
    public static string EvaluatePath(Context context, string path)
    {
      if (ID.IsID(path))
        return path;

      string workingPath = string.Empty;
      if (!path.StartsWith("/"))
        workingPath = context.CurrentItem.Paths.FullPath + "/" + path;
      else
        workingPath = path;

      // Strip any language and version tags
      if (workingPath.IndexOf(':') >= 0)
        workingPath = workingPath.Substring(0, workingPath.IndexOf(':'));

      // Make relative paths absolute
      string[] parts = workingPath.Split('/');
      StringCollection targetParts = new StringCollection();
      targetParts.AddRange(parts);

      while (targetParts.Contains(".."))
      {
        int ind = targetParts.IndexOf("..");
        targetParts.RemoveAt(ind);
        if (ind > 0)
        {
          targetParts.RemoveAt(ind - 1);
        }
      }

      if (targetParts[targetParts.Count - 1] == ".")
        targetParts.RemoveAt(targetParts.Count - 1);

      // Remove empty elements
      while (targetParts.Contains(""))
      {
        targetParts.RemoveAt(targetParts.IndexOf(""));
      }

      string[] toRet = new string[targetParts.Count];
      targetParts.CopyTo(toRet, 0);
      return "/" + string.Join("/", toRet);
    }
Пример #22
0
        public static Dictionary<string, Color> StringCollectionToDictionary(StringCollection stringCollection)
        {
            if (stringCollection == null || stringCollection.Count == 0)
            {
                return new Dictionary<string, Color>();
            }

            string[] strings = new string[stringCollection.Count];
            stringCollection.CopyTo(strings, 0);

            string[] names = strings.Where((s, i) => i % 2 == 0).ToArray();
            string[] colors = strings.Where((s, i) => i % 2 == 1).ToArray();
            if (names.Count() != colors.Count())
            {
                // There's a problem. Data is junk. Return empty dictionary.
                return new Dictionary<string, Color>();
            }

            var dict = new Dictionary<string, Color>();
            for (int i = 0; i < names.Count(); i++)
            {
                Color color;
                try
                {
                    color = ColorTranslator.FromHtml(colors[i]);
                }
                catch
                {
                    // Just do hot pink
                    color = Color.HotPink;
                }

                dict[names[i]] = color;
            }

            return dict;
        }
 public static string[] GetDatabases(string connectionString, int? commandTimeOut)
 {
     SqlConnection sqlConnection = null;
     string[] databasesArray;
     StringCollection databasesCollection = new StringCollection();
     try
     {
         sqlConnection = new SqlConnection(connectionString.TrimEnd(';') + ";Connection Timeout=" + commandTimeOut.ToString());
         sqlConnection.Open();
         string sqlversion = sqlConnection.ServerVersion;
         sqlversion = sqlversion.Split('.')[0]; //major version
         int intsqlversion = Convert.ToInt32(sqlversion);
         string sql = String.Empty;
         if (intsqlversion >= 9)
             sql = "use master; select name from sys.databases order by name";
         else
             sql = "use master; select name from sysdatabases order by name";
         SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
         if (commandTimeOut.HasValue)
             sqlCommand.CommandTimeout = commandTimeOut.Value;
         SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
         while (sqlDataReader.Read())
         {
             databasesCollection.Add(sqlDataReader["name"].ToString());
         }
         sqlDataReader.Close();
         databasesArray = new string[databasesCollection.Count];
         databasesCollection.CopyTo(databasesArray, 0);
         return databasesArray;
     }
     finally
     {
         if (sqlConnection != null && sqlConnection.State == ConnectionState.Open)
             sqlConnection.Close();
     }
 }
Пример #24
0
            internal static string[] GetValues(ListViewEntry lve)
            {
                StringCollection vals = new StringCollection();

                foreach (ListViewField lvf in lve.listViewFieldList)
                {
                    vals.Add(lvf.formatPropertyField.propertyValue);
                }
                if (vals.Count == 0)
                    return null;
                string[] retVal = new string[vals.Count];
                vals.CopyTo(retVal, 0);
                return retVal;
            }
Пример #25
0
 internal static string[] GetProperties(ListViewEntry lve)
 {
     StringCollection props = new StringCollection();
     foreach (ListViewField lvf in lve.listViewFieldList)
     {
         props.Add(lvf.label ?? lvf.propertyName);
     }
     if (props.Count == 0)
         return null;
     string[] retVal = new string[props.Count];
     props.CopyTo(retVal, 0);
     return retVal;
 }
Пример #26
0
        private string[] GetLines( StringCollection sc )
        {
            string[] tmp = new string[ sc.Count ];

            sc.CopyTo( tmp, 0 );

            return tmp;
        }
 public static void SetFileDropList(StringCollection filePaths)
 {
     if (filePaths == null)
     {
         throw new ArgumentNullException("filePaths");
     }
     if (filePaths.Count == 0)
     {
         throw new ArgumentException(System.Windows.Forms.SR.GetString("CollectionEmptyException"));
     }
     foreach (string str in filePaths)
     {
         try
         {
             Path.GetFullPath(str);
         }
         catch (Exception exception)
         {
             if (System.Windows.Forms.ClientUtils.IsSecurityOrCriticalException(exception))
             {
                 throw;
             }
             throw new ArgumentException(System.Windows.Forms.SR.GetString("Clipboard_InvalidPath", new object[] { str, "filePaths" }), exception);
         }
     }
     if (filePaths.Count > 0)
     {
         System.Windows.Forms.IDataObject data = new DataObject();
         string[] array = new string[filePaths.Count];
         filePaths.CopyTo(array, 0);
         data.SetData(DataFormats.FileDrop, true, array);
         SetDataObject(data, true);
     }
 }
Пример #28
0
 /// <summary>
 /// 字符串集合转换成字符串数组。
 /// </summary>
 /// <param name="collection">需要转化为字符串数组的字符串集合。</param>
 /// <returns>转化后的字符串数组,如果传入集合为null则返回0长度的字符数组。</returns>
 public static string[] ToStringArray(StringCollection collection)
 {
     if (collection == null)
     {
         return new string[0];
     }
     string[] array = new string[collection.Count];
     collection.CopyTo(array, 0);
     return array;
 }
Пример #29
0
 /// <summary>
 /// 获取本机IPV4 IP
 /// </summary>
 /// <param name="LocalIP"></param>
 /// <returns></returns>
 public static string[] GetLocalIpv4(out string LocalIP)
 {
     LocalIP = string.Empty;
     //事先不知道ip的个数,数组长度未知,因此用StringCollection储存
     IPAddress[] localIPs;
     localIPs = Dns.GetHostAddresses(Dns.GetHostName());
     StringCollection IpCollection = new StringCollection();
     foreach (IPAddress ip in localIPs)
     {
         //根据AddressFamily判断是否为ipv4,如果是InterNetWorkV6则为ipv6
         if (ip.AddressFamily == AddressFamily.InterNetwork)
         {
             LocalIP = ip.ToString();
             IpCollection.Add(ip.ToString());
         }
     }
     string[] IpArray = new string[IpCollection.Count];
     IpCollection.CopyTo(IpArray, 0);
     return IpArray;
 }
Пример #30
0
        private String[] GetArrayFromStringCollection(StringCollection strCollection)
        {
            String[] returnString;
            if (strCollection == null)
            {
                returnString = new String[0];
            }
            else
            {
               returnString = new String[strCollection.Count];

                strCollection.CopyTo(returnString, 0);
            }

            return returnString;
        }
Пример #31
0
        /// <summary> 
        /// Set the file drop list to Clipboard. 
        /// </summary>
        public static void SetFileDropList(StringCollection fileDropList) 
        {
            if (fileDropList == null)
            {
                throw new ArgumentNullException("fileDropList"); 
            }
 
            if (fileDropList.Count == 0) 
            {
                throw new ArgumentException(SR.Get(SRID.DataObject_FileDropListIsEmpty, fileDropList)); 
            }

            foreach (string fileDrop in fileDropList)
            { 
                try
                { 
                    string filePath = Path.GetFullPath(fileDrop); 
                }
                catch (ArgumentException) 
                {
                    throw new ArgumentException(SR.Get(SRID.DataObject_FileDropListHasInvalidFileDropPath, fileDropList));
                }
            } 

            string[] fileDropListStrings; 
 
            fileDropListStrings = new string[fileDropList.Count];
            fileDropList.CopyTo(fileDropListStrings, 0); 

            SetDataInternal(DataFormats.FileDrop, fileDropListStrings);
        }