I have been learning c# for a short time and am creating some desktop project. I would like to add an empty text file using RadWindow.Prompt its name and then add the text file for editing. Currently this is handled using openFileDialog.
The principle of operation should resemble adding a file in OneNote, if anyone has used it. RadWindow.Prompt will display a window in which the user will type the name of the file he wants to create and then the file will be added, but it will be an empty file for editing (text document).
I would ask for a hint.
private async void AddFile(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog openFileDialog = new OpenFileDialog();
bool response = openFileDialog.ShowDialog();
if (response == true)
{
string filepath = openFileDialog.FileName;
string fileName = Path.GetFileName(filepath);
try
{
File.Copy(filepath, Settings[0].SettingValue + "\\" + fileName, true);
long size = 1024;
await _db.FileInsert(1, fileName, size, Settings[0].SettingValue + "\\" + fileName, "a", "FileAddTest", "FileAddTest");
MessageBus.Default.Publish(new RefreshMessage(this, "Refresh"));
}
catch
{
RadWindow.Alert("File not add");
}
}
}
Maybe instead of that, create model with for example two properties and add to DB context.
code concept:
class File
{
public string FileName {get;set;}
[Column(TypeName="text")]
public string FileContent {get;set;}
}
void SomeAddFileButton()
{
var file = new File()
{
FileName = someInputField.Text;
};
dbContext.Files.Add(file);
}
EF Core: https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app
'text' type: https://learn.microsoft.com/en-us/sql/t-sql/data-types/ntext-text-and-image-transact-sql
Related
I have a Winform control to write notes whose contents are periodically uploaded to the server.
I need to create a local file as a backup to save the contents of the notes.
When I type text into the notebox, the content remains in the note box and gets saved into the local text file. However, when I enter more texts to the note-box, the previous content as well as the new content gets appended to the local file.
How do I make sure that only the recent content gets appended to the local file? If i clear the note-box content, no content gets logged on to the server.
private void btnNote_Click(object sender, EventArgs e)
{
Note noteFrm = new Note();
//set Note Text
noteFrm.NoteText = _timeCard.NoteText;
if (noteFrm.ShowDialog() == DialogResult.OK)
{
//Save notes locally as well
string path = #"C:\QB Notes\";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string projname = this._timeCard.Project.ProjectName.TrimEnd()+".txt";
string fileloc = path + projname;
// FileStream fs = null;
if (!File.Exists(fileloc))
{
using (TextWriter txt = new StreamWriter(fileloc))
{
// TextWriter txt = new StreamWriter(fileloc);
txt.Write(noteFrm.NoteText + Environment.NewLine);
txt.Close();
}
}
else if (File.Exists(fileloc))
{
using (var txt = new StreamWriter(fileloc, true))
{
txt.BaseStream.Seek(0, SeekOrigin.End);
txt.Write(noteFrm.NoteText + Environment.NewLine);
txt.Close();
}
}
//noteFrm.NoteText="";
//get Note Text
_timeCard.NoteText = noteFrm.NoteText;
Utils.LogManager.write("New Note Text: " + noteFrm.NoteText);
}
}
If you want the file to always match what is in the text box, then I'd suggest that you replace your whole if (!File.Exists(fileloc)) block with just this:
File.WriteAllText(fileloc, noteFrm.NoteText + Environment.NewLine);
That will create the file if needed, open the file, replace all the contents with what is in the text box, and close the file.
I am trying to upload files with same names to the server using GUID, but its not working and is still replacing the old files, can anybody help me by telling where I am making the mistake?
here is y code to upload:
protected void btnAddExpenditure_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string FileName = FileUpload1.PostedFile.FileName;
if (File.Exists(FileName))
{
FileName = Guid.NewGuid() + FileName;
}
//check file Extension & Size
int filesize = FileUpload1.PostedFile.ContentLength;
if (filesize > (20 * 1024))
{
Label1.Text = "Please upload a zip or a pdf file";
}
string fileextention = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileextention.ToLower() != ".zip" && fileextention.ToLower() != ".pdf")
{
Label1.ForeColor = System.Drawing.Color.Green;
Label1.Text = "Please upload a zip or a pdf file";
}
else
{
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//save file to disk
FileUpload1.SaveAs(Server.MapPath("Reciepts/" + ReceiptFileName));
}
string FileName = FileUpload1.PostedFile.FileName;
if (File.Exists(FileName))
{
FileName = Guid.NewGuid() + FileName;
}
...
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
Here's your problem. You're creating a new string variable that holds the file name (FileName). If it exists, you modify FileName with a new GUID. But at the very end...
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
you're still using the original FileUpload1.PostedFile.FileName. This should be changed to
string ReceiptFileName = Path.GetFileName(FileName);
EDIT: Reading through the code again, I think you may have other problems as well. Assuming that FileUpload1.PostedFile.FileName is a full path (i.e. C:\Folder\File.txt), then
FileName = Guid.NewGuid() + FileName;
would result in something like 123-4321-GUIDC:\Folder\File.txt
I doubt that's what you want. You might want to flip that around
FileName = FileName + Guid.NewGuid();
I have a Dropdown list & file uploader.Here i need, when dropdown list selected & after that need to load the file uploader.In my coding always it shows there's no File.
Here i need SelectedValue passes to the database with file uploader.
My Code
protected void drpuser_SelectedIndexChanged(object sender, EventArgs e)
{
Guid SelectedUserId =Guid.Parse(drpuser.SelectedValue);
FileUploader();
}
FileUploader
public void FileUploader()
{
// var user = Membership.GetUser();
if (Roles.IsUserInRole("Administrator"))
{
Guid SelectedUserId = Guid.Parse(drpuser.SelectedValue); //<-- value correct
foreach (string s in Request.Files)
{
HttpPostedFile file = Request.Files[s];
int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = "";
if (!string.IsNullOrEmpty(fileName))
fileExtension = Path.GetExtension(fileName);
Guid UserGUID = (Guid)Membership.GetUser().ProviderUserKey;
string UserFolderPath = "~/UploadedFiles/" + UserGUID;
System.IO.Directory.CreateDirectory(Server.MapPath(UserFolderPath));
string savedFileName = Path.Combine(Server.MapPath(UserFolderPath), fileName);
string FullPath = UserFolderPath + "/" + fileName;
file.SaveAs(savedFileName);
DataAccess da = new DataAccess();
da.AddAdminFiles(UserGUID, FullPath, DateTime.Now, true, SelectedUserId);
}
}
else
{
}
I'm thinking that the file will only be posted on actual submit.. Im not sure if an AutoPostBack will automatically submit file over and over.. probably too much HTTP Overhead.
If you can, add a "submit" button instead, and have the user choose an item from the drop down list and supply a file. Then when user submits, look for the HTTP file, and it should be in the Request Object.
which i used earlier (FileuploadControl tool used)
inside button click method
if (FileUploadControl.HasFile)
{
filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
string lines;
string root = Server.MapPath("~/");
string Template = root + filename;
using (StreamReader reader = new StreamReader(Template))
{
while ((lines = reader.ReadLine()) != null)
list.Add(lines); // Add to list.
}
//file is now in list
//MORE IMPORTANT CODE
}
But now I am just using FolderDialog
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.ShowNewFolderButton = true;
DialogResult result = folderDialog.ShowDialog();
if (result == DialogResult.OK) {
textBox8.Text = folderDialog.SelectedPath;
Environment.SpecialFolder root = folderDialog.RootFolder
//...
}
How can i read the file so that i can only use the FolderBrowserDialog to read an entire file and extract data?
I guess you are working in Windows Forms now if you are using FolderDialog.
You should use better OpenFileDialog if you want the user to check a FILE, not a Folder.
You can read the file using System.IO classes once you have the path.
If the file is text for example you can do:
string FinalPath = OpenFileDialog.FileName;
string Text= System.IO.File.ReadAllText(FinalPath);
you can also read the file into byte()
byte[] file = System.IO.File.ReadAllBytes(FinalPath);
I'm using Microsoft Expression Encoder and this is my code
using (LiveJob job = new LiveJob())
{
// Creates file source for encoding
LiveFileSource fileSource = job.AddFileSource(DataDirectory);
// Sets playback to loop on reaching the end of the file
fileSource.PlaybackMode = FileSourcePlaybackMode.Jump;
// Sets this source as the current active one
job.ActivateSource(fileSource);
job.ApplyPreset(LivePresets.VC1IISSmoothStreamingLowBandwidthStandard);
PushBroadcastPublishFormat format = new PushBroadcastPublishFormat();
format.PublishingPoint = new Uri(PublishPoint);
job.PublishFormats.Add(format);
// Starts encoding
job.StartEncoding();
}
this code encode a list of files in a directory when he finish one he jump to the next
what I want to do is change the file name when it's encoded before passing to th other one
I have added this Methode I don't know if it work or no
public void liveJob_Status(object sender, EncodeStatusEventArgs e)
{
if (e.Status == EncodeStatus.Jumped)
{ LiveFileSource file = (LiveFileSource)e.LiveSource;
string name = file.Name;
string modified_name = "Encode" + name;
File.Move(DataDirectory + #"\" + name, DataDirectory + #"\" + name.Replace(name, modified_name));
}
}