C#: newbie Questions creating strings and passing and returning variables to functions

Hi

I have some c# 'Best Practice' questions I would like help with

first if you drag a directory with spaces onto the console how do you deal with the added quote marks?
"C:\My Path" becomes "\"C;\\My Path\""
or no space
"C:\MyPath" becomes "C;\\My Path"

Open in new window


Second how do you create a variable eg a string to use later?
Third how do you pass a string into a function or method and get back a bool and a string

I've created some sudo  code to illustrate what I'm asking ( I know it's not correct)

   
using System;
using System.IO;

class Program
{
   public string BaseFold { get; set; } ;// Needed to use throughout program
   static void Main()
    {

	Console.WriteLine("Drag Base Directory");
	// How do you deal with paths with spaces?
	
	BaseFold = Console.ReadLine();

	\\ example from add watch "\"C;\\My Path\\has Space\"\"

        for (int i = 0; i < 10; i++)
        {
		string fName;
		// Is this the best way to create a string for later use?
		if(Condition1)
		 {
		   fName = "ABC" + i + ".txt";
		 }

		if(Condition2)
		 {
		   fName = "XYZ" + i + ".txt";
		 }
               // How to pass a string and get back a bool and a string
		bool FileFound, FinalPath = FileExists(fName);
		if(FileFound == true)
		{

	            Console.WriteLine("Found File at " + FinalPath );
		}
        }
    }
   public string  FileExists(string fName)
    {
	string FinalPath;
	
	  bool FileFound = false;
	string SubDirA = BaseFold + @"\SubDirA";
	string SubDirB  = BaseFold + @"\SubDirB";
	if(Directory.Exists(SubDirA))
	  {
           if(File.Exists(SubDirA + "\\" + fName) )
	    {
		FinalPath = SubDirA + "\\" + fName;
		FileFound = true;
	    }
	  }
	if(Directory.Exists(SubDirB))
	  {
           if(File.Exists(SubDirB + "\\" + fName) )
	    {
		FinalPath = SubDirB + "\\" + fName;
		FileFound = true;
	    }
	  }
	  if(FileFound == true)
	  {
	    return FileFound , FinalPath;
	  }
       
    }
}
 

Open in new window

LVL 1
trevor1940Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kyle AbrahamsSenior .Net DeveloperCommented:
Pass one as a reference:
bool FileFound;
FileFound = FileExists(ref fName);
//ref will modify the fName variable permanently.



   public bool FileExists(ref string fName)
    {
	string FinalPath;
	
	  bool FileFound = false;
	string SubDirA = BaseFold + @"\SubDirA";
	string SubDirB  = BaseFold + @"\SubDirB";
	if(Directory.Exists(SubDirA))
	  {
           if(File.Exists(SubDirA + "\\" + fName) )
	    {
		FinalPath = SubDirA + "\\" + fName;
		FileFound = true;
	    }
	  }
	if(Directory.Exists(SubDirB))
	  {
           if(File.Exists(SubDirB + "\\" + fName) )
	    {
		FinalPath = SubDirB + "\\" + fName;
		FileFound = true;
	    }
	  }
	  if(FileFound == true)
	  {
                fName = FinalPath;
	    
	  }
      return FileFound;
       
    }

Open in new window

0
Fernando SotoRetiredCommented:
Assuming we are dragging a file path from the file explorer window to the Command Prompt/Console the  quotation marks are needed so leave as is.

To your question, "Second how do you create a variable eg a string to use later?", You create a variable outside of any function but still within a class and that variable will be available to everything in that class.

To the question, "Third how do you pass a string into a function or method and get back a bool and a string", Something like this
// Call the Function
var retTuple = TestFunction("Test Input");
// Display the returned values
Console.WriteLine("String : {0}  Bool : {1}", retTuple.Item1, retTuple.Item2);

...

public Tuple<string, bool> TestFunction(string input){
    string retStr = "String value";
    bool retBoo = true;
    
    return Tuple.Create(retStr, retBoo);
}

Open in new window

The Tuple Class
0
trevor1940Author Commented:
Are you saying it is ok to create a string like this

string MyString;
            if (MyString != "")
            {
                
                //Error CS0165  Use of unassigned local variable 'MyString' ConsoleApplication1
            }

Open in new window


Assuming we are dragging a file path from the file explorer window to the Command Prompt/Console the  quotation marks are needed so leave as is.

You can leave as is if there are no spaces in the path and concatenate like this

          Console.WriteLine("Enter Folder To Save");
            string BaseFold = Console.ReadLine();

            string FullPath = BaseFold + "\\test.txt";
            Console.WriteLine(FullPath);
            Console.ReadLine();

Outputs
Enter Folder To Save
D:\temp\MyPath
D:\temp\MyPath\test.txt

Open in new window



however if you have a space

Outputs
Enter Folder To Save
"D:\temp\My Path"
"D:\temp\My Path"\test.txt

Open in new window


see attached
File.jpg
0
Become a Certified Penetration Testing Engineer

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

Kyle AbrahamsSenior .Net DeveloperCommented:
Initialize this to avoid issues:
string MyString = "";
            if (MyString != "")
            {
              
                //no more error;
            }

Open in new window


Technically you should remove the trailing quote and re-encapsulate.  EG:  "D:\temp\My Path\test.txt"

You can use the following functions:
string.EndsWith(@""""); //determine if the path ends with a quote
string.Trim(new char[] { ' " '})  // remove the spaces, typed in here for clarity.  This will remove the last quote from the end of the path.

so function would look like:
if basePath.EndsWith(@""""")
{
    // remove the quote from the quote from the base path, add it to the end of the file
}
else
{
  // just append the file to the path.
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
trevor1940Author Commented:
Wow 4 Quote marks thought it was a typo at first but the code bellow worked
When cleaning / manipulating strings like this is it good practice to reassign the string onto it's self?  

          Console.WriteLine("Enter Folder To Save");
            string BaseFold = Console.ReadLine();
       string FullPath ="";
         if(BaseFold.EndsWith(@""""))
            {
               BaseFold = BaseFold.Trim(new char[] {'"'}); 
                Console.WriteLine("trimed " + BaseFold);
            }    
               FullPath = BaseFold + "\\test.txt"; 
        Console.WriteLine(FullPath);

Open in new window


I've seen this used to initiate strings
public string Name { get; set; }

Open in new window


When do you use this and not

string Name ="";

Open in new window

0
Kyle AbrahamsSenior .Net DeveloperCommented:
public string Name { get; set; } = "";

You would use the get/set model in a more object oriented approach.

Take a more real life example:
private int _BankAccountBalance; // this is the field that the class will use and write to.

public int BankAccountBalance  // this is the property which you expose.  It can contain custom logic to ensure proper values in the field.
{
   get 
        {
                 if (HasPermissions())
                           return _BankAccountBalance;
                  else
                     throw new error "Unauthorized access";
        }
   set
         {
                    if (value >= 0) 
                       _BankAccountBalance = value;
                    else
                       throw new error "Bank account balance must be greater than 0";
                   
          }
}

Open in new window


The four quotes work because 2 double quotes is really one single quote in the string, and then you need begging and ending quotes.

EG:
"This is a normal string"  <--- One quote on each side to start and end string.
" ""This is a quote using quotation marks"" "   is Output text of  "This is a quote using quotation marks".  <--- Start and end quotes + 2 more on each side to say you want a quote in the string.



For "Best Practice" in terms of reusing strings if you're building something then yes, it would make sense to re-use it.  It all depends on what you think makes your code the most clear.

I personally like building up different parts where able.  EG:  I agree with having a base Path variable that you wouldn't overwrite /append on to.

So if base path  = @"C:\Code\"
then check basePath + "Dir1\" and basePath + "Dir2\"

found:
Fullpath = basePAth
FullPath += "Dir1\"
fullPath += FileName

Something along those lines.  I'm being verbose in the code just to show you when I would and wouldn't re-use the variable.

The trick really is to assign a job to each variable.  EG:  You created the variable, what's it's purpose.  If you're ammending the variable to help achieve that purpose, then re-use it.  When it's accomplished the goal then it should no longer be changed.

Hope that helps.
0
trevor1940Author Commented:
Thank you for your help and explanations
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.