Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
So Dai fixed my problem with the openfiledialog but then i started working on save file,
here is the code i made but it did not work/ i can't think of a way to get it to work.
const String FILTER_LUA = "Lua scripts (*.lua)|*.lua";
const String FILTER_TXT = "Text files (*.txt)|*.txt";
const String FILTER_ALL = "All files (*.*)|*";
// ...
SaveFileDialog sfd = new SaveFileDialog()
{
// InitialDirectory = AppDomain.CurrentDomain.BaseDirectory,
InitialDirectory = Environment.CurrentDirectory,
Filter = FILTER_LUA + "|" + FILTER_TXT + "|" + FILTER_ALL,
Title = "Open Script"
};
Boolean? result = sfd.ShowDialog();
if ((result ?? false) && File.Exists(sfd.FileName))
{
String fileText = File.ReadAllText(sfd.FileName);
this.TextEditor.Text = fileText;
}
SaveFileDialog is meant to pick a file path to save data to. In your case you would have to write the TextEditor.Text value to the picked file using the File.WriteAllText or the asynchronous File.WriteAllTextAsync method:
private const string FILTER_LUA = "Lua scripts (*.lua)|*.lua";
private const string FILTER_TXT = "Text files (*.txt)|*.txt";
private const string FILTER_ALL = "All files (*.*)|*";
private async Task SaveTextBoxToFileAsync()
{
var sfd = new SaveFileDialog()
{
// InitialDirectory = AppDomain.CurrentDomain.BaseDirectory,
InitialDirectory = Environment.CurrentDirectory,
Filter = $"{FILTER_LUA}|{FILTER_TXT}|{FILTER_ALL}",
Title = "Open Script"
};
bool? result = sfd.ShowDialog();
if (result ?? false)
{
await File.WriteAllTextAsync(sfd.FileName, this.TextEditor.Text);
}
}
Usage
await SaveTextBoxToFileAsync();
Related
This question already has answers here:
How do I determine a mapped drive's actual path?
(14 answers)
Closed 2 years ago.
I have ran into an issue where by when the user adds a file directory to my project the link is stored as their own mapped drive. For example;
C:\Location\Location
However, some users may have the C: drive on the server mapped as M: for example. Thus are unable to locate the file.
What I would like to do is replace this with the actual server name, ie
\\ArtServer\
I know that I could achieve this by replacing the opening part of the string, however if more servers are added in the future then this will obviously fallover in a huge mess. Currently the user grabs the file path using a standard get file dialogue;
public static string GetFilePath(string filter = "All Files (*.*)|*.*", string initialDirectory = #"This PC")
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = filter;
fileDialog.FilterIndex = 1;
fileDialog.Multiselect = false;
fileDialog.InitialDirectory = Directory.Exists(initialDirectory) ? initialDirectory : #"This PC";
if (fileDialog.ShowDialog() == true)
{
return fileDialog.FileName;
}
else
{
return null;
}
}
Is there anyway I can achieve this with what I currently have?
Thank you to #ADyson for all of your help. I decided to use an answer provided by ibram from the thread linked above. For anyone else who has the same issue I have posted what I had done;
public static string GetUNCPath(string path)
{
if (path.StartsWith(#"\\"))
{
return path;
}
ManagementObject mo = new ManagementObject();
mo.Path = new ManagementPath(String.Format("Win32_LogicalDisk='{0}'", path));
// DriveType 4 = Network Drive
if (Convert.ToUInt32(mo["DriveType"]) == 4)
{
return Convert.ToString(mo["ProviderName"]);
}
else
{
return path;
}
}
public static string GetFilePath(string filter = "All Files (*.*)|*.*", string initialDirectory = #"This PC")
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = filter;
fileDialog.FilterIndex = 1;
fileDialog.Multiselect = false;
fileDialog.InitialDirectory = Directory.Exists(initialDirectory) ? initialDirectory : #"This PC";
if (fileDialog.ShowDialog() == true)
{
// Split the file directory to gain root path
// Use GetUNCPath to convert root path to server name
string s = fileDialog.FileName;
int index = s.IndexOf(':') + 1;
string rootPath = GetUNCPath(s.Substring(0, index));
string directory = s.Substring(index);
return rootPath + directory;
}
else
{
return null;
}
}
I was asked to make a file copier that will change the name of a file, by adding "_Copy", but will keep the type of file.
For example:
c:\...mike.jpg
to:
c:\...mike_Copy.jpg
Here is my code:
private void btnChseFile_Click(object sender, EventArgs e)
{
prgrssBar.Minimum = 0;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Which file do you want to copy ?";
DialogResult fc = ofd.ShowDialog();
tbSource.Text = ofd.FileName;
tbDestination.Text = tbSource.Text + "_Copy";
}
You can use the classes System.IO.FileInfo and System.IO.Path to do what it appears you are attempting:
OpenFileDialog od = new OpenFileDialog();
if(od.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
System.IO.FileInfo fi = new System.IO.FileInfo(od.FileName);
string oldFile = fi.FullName;
string newFile = oldFile.Replace(System.IO.Path.GetFileNameWithoutExtension(oldFile),
string.Format("{0}_Copy",
System.IO.Path.GetFileNameWithoutExtension(oldFile)));
MessageBox.Show(newFile);
}
Then you can call the following to perform the copy:
System.IO.File.Copy(oldFile, newFile);
You are appending the _Copy onto the end of the filename and not before the extension. You need to add it before the extension:
string destFileName = $"{Path.GetFileNameWithoutExtension(ofd.FileName)}_Copy{Path.GetExtension(ofd.FileName)}";
Or without C# 6:
string destFileName = String.Format("{0}_Copy{1}",
Path.GetFileNameWithoutExtension(ofd.FileName),
Path.GetExtension(ofd.FileName));
Then to get the full path to the file use:
string fullPath = Path.Combine(Path.GetDirectoryName(ofd.FileName, destFileName));
Then to perform the actual copy just use:
File.Copy(ofd.FileName, fullPath);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
openFileDialog1.Filter = "JPEG (*.jpg)|*.jpg|PNG (*.png)|*.png|GIF (*.gif)|*.gif";
openFileDialog1.ShowDialog();
string name = openFileDialog1.FileName;
FileInfo F = new FileInfo(name);
string path = F.DirectoryName.ToString();
pictureBox1.Load(path);
OpenDialog.Reset();
OpenDialog.AutoUpgradeEnabled = true;
OpenDialog.CheckFileExists = true;
OpenDialog.CheckPathExists = true;
OpenDialog.DefaultExt = "";
OpenDialog.FileName = "";
OpenDialog.Filter = "Images (.jpeg)|*.jpg;*.jpeg";
OpenDialog.InitialDirectory = #"C:\";
OpenDialog.Multiselect = false;
OpenDialog.RestoreDirectory = false;
OpenDialog.ShowHelp = false;
OpenDialog.ShowReadOnly = false;
OpenDialog.Title = this.Text;
if (OpenDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Image productimage = Image.FromFile(OpenDialog.FileName);
System.Drawing.Size defaultsize = new Size(129, 129);
if (productimage.Width > defaultsize.Width || productimage.Height > defaultsize.Height)
{
Common.ShowErrorMessage("Cannot load large image. Default size (128 X 128)", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
PicBox.Image = productimage;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to read the File by Splitting each Row by removing whitespace through regex.split in c# but my code isn't working properly need help. Thanks in Advance.
text="";
OpenFileDialog open = new OpenFileDialog();
if (open.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Stream filestream = open.OpenFile();
if (filestream != null)
{
string filename = open.FileName;
text = File.ReadAllText(filename);
}
string code = textBox1.Text;
columncounter = code.Length;
string[] arrays = Regex.Split(code, #"\s+");
textBox1.Text = text;
}
If you are trying to write each row, without whitespace, to your TextBox, this should work:
var result = new StringBuilder();
foreach (var line in File.ReadAllLines(filename))
{
result.AppendLine(Regex.Replace(line, #"\s", "")));
}
textBox1.Text = result.ToString();
For faster performance, use string.Replace:
var result = new StringBuilder();
foreach (var line in File.ReadAllLines(filename))
{
result.AppendLine(line
.Replace("\t", "")
.Replace("\n", "")
.Replace("\r", "")
.Replace(" ", ""));
}
textBox1.Text = result.ToString();
Just add textBox1.text = string.Concat(arrays). It will concatenate the strings from the splitted array.
or you could do something like text.Replace(" ", "")
In my app I used OpenFileDialog to select a file from temp location (%temp%). Now when I again use OpenFileDialog, it opens from some other location. This feature is working fine if any folder other than temp is selected.
Is this a bug or a feature or Technical limitation?
I wrote this code.
public string[] OnOpenFile(string filetype)
{
string strReturn = null;
string[] strFilename = null;
System.Windows.Forms.OpenFileDialog fdlg = new System.Windows.Forms.OpenFileDialog();
fdlg.Title = "Select an Excel file to Upload.";
fdlg.Filter = filetype;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
strFilename = fdlg.FileNames;
}
return strFilename;
}
You can use InitialDirectory property documented at http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.initialdirectory.aspx
in your example:
fdlg.InitialDirectory = Path.GetTempPath();
Running this C# Proram in LinqPad produces wanted result
void Main()
{
OnOpenFile();
OnOpenFile();
OnOpenFile();
}
public string[] OnOpenFile()
{
string strReturn = null;
string[] strFilename = null;
System.Windows.Forms.OpenFileDialog fdlg = new System.Windows.Forms.OpenFileDialog();
fdlg.Title = "Select an Excel file to Upload.";
//fdlg.Filter = filetype;
fdlg.InitialDirectory = Path.GetTempPath();
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
strFilename = fdlg.FileNames;
}
return strFilename;
}
If you comment
fdlg.InitialDirectory = Path.GetTempPath();
you can achieve wanted behavior.
Each time file is selected in folder, that folder in OpenFileDialog opens.
If you press Cancel you have to handle your selected path diffrently - in some string variable, then when you open OpenFileDialog again you set InitialDirectory